Take for example this array:
[{id: 0, weight: 200}
{id: 0, weight: 200}
{id: 1, weight: 75}
{id: 2, weight: 5}]
I need to get it a result of :
[ {id:0, times:2},
{id:1, times:1},
{id:2, times:1}]
You could reduce the array into a new array with the count
var arr = [
{ id: 0, weight: 200 },
{ id: 0, weight: 200 },
{ id: 2, weight: 75 },
{ id: 9, weight: 5 }
];
var arr2 = arr.reduce( (a,b) => {
var i = a.findIndex( x => x.id === b.id);
return i === -1 ? a.push({ id : b.id, times : 1 }) : a[i].times++, a;
}, []);
console.log(arr2)
This simple reducer will return an array of arrays, each one containing all the duplicate elements in the original array.
function groupDuplicates(array, compareF) {
return array.reduce((acc, item) => {
const existingGroup = acc.find(g => (compareF(g[0], item)));
if (existingGroup) {
existingGroup.push(item);
} else {
acc.push([item])
}
return acc;
}, []);
}
Where compareF is your custom comparator, and should returns true if it's parameters are considered to be equal.
NOTE: In this implementation, non duplicated items will remain as the only element in their array. You may want to filter these out later, like so:
const duplicatesOnly = groupDuplicates(myArray, myComparator).filter(i => (i.length > 1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With