I am trying to find all the objects that contain the same key value pair and create a new array of objects with the duplicate objects with the number of times they were found.
For example, if two objects contain the key value pair, type: 'apples'
, an output object should represent the value, in this case, 'apples', and the number of times it appeared, twice.
Here is an example:
const inventory = [
{ type: 'apples' },
{ type: 'bananas' },
{ type: 'apples' },
{ type: 'orange' },
{ type: 'orange' },
{ type: 'orange' },
];
const duplicates = inventory.reduce((acc, item) => {
let newItem = acc.find((i) => i.type === item.type); // check if an item with the current type exists
if (newItem) {
// create a new object w/ new shape
item.name = item.type;
item.count = 1;
acc.push(item);
} else {
// object exists -> update count
item.count += 1;
}
return acc;
}, []);
console.log(duplicates);
// Successful output array
// duplicates = [
// {
// name:'apples',
// count:2
// },
// {
// name:'bananas',
// count:1
// }
// {
// name:'oranges',
// count:3
// }
// ]