I need to count how much each object repeats by id in array and create new array which will have values like 'id' of object and number of repeats in array as 'count'. I try to use reduce but I think use it wrong. Try to find answer but didn't find variant with creating new array with objects.
// Array which I have
[
{ name: 'One', id: 3 },
{ name: 'Two', id: 1 },
{ name: 'Three', id: 2 },
{ name: 'Four', id: 1 }
]
// Array which I need to create
[
{ id: 3, count: 1 },
{ id: 1, count: 2 },
{ id: 2, count: 1 },
]
//I have try this code, but it return array with counts [1, 2, 1]
const results = Object.values(arr.reduce((acc, { id }) => {
acc[id] = (acc[id] || 0) + 1;
return acc;
}, {}));
Thank you!