Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reduce an array and add a count as a new field?

I have an array of objects, however i need the array to add a count onto each object, and also remove any duplicates. Is there a simple way to achieve this?

CURRENT

[
 { id: 2, name: ‘Adventure’ },
 { id: 6, name: ‘Crime’ },
 { id: 2, name: ‘Adventure’ },
 { id: 3, name: ‘Beautiful’ },
 { id: 7, name: ‘Drama’ },
 { id: 2, name: ‘Adventure’ }
]

EXPECTED

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    [
     { id: 2, name: ‘Adventure’, count: 3 },
     { id: 6, name: ‘Crime’, count: 1 },
     { id: 3, name: ‘Beautiful’, count: 1 },
     { id: 7, name: ‘Drama’, count: 1 }
    ]

>Solution :

One way to achieve this would be to use a combination of the Array.map() and Array.filter() methods.

The Array.map() method can be used to add the count property to each object in the array, and the Array.filter() method can be used to remove any duplicates.

Here is an example of how you could implement this:

let arr = [
  { id: 2, name: 'Adventure' },
  { id: 6, name: 'Crime' },
  { id: 2, name: 'Adventure' },
  { id: 3, name: 'Beautiful' },
  { id: 7, name: 'Drama' },
  { id: 2, name: 'Adventure' }
];

// Use the map method to add the count property to each object
let updatedArr = arr.map(item => {
  return {
    id: item.id,
    name: item.name,
    count: arr.filter(i => i.id === item.id).length
  };
});

// Use the filter method to remove duplicates
updatedArr = updatedArr.filter((item, index) => updatedArr.findIndex(i => i.id === item.id) === index);

console.log(updatedArr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading