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
[
{ 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);