How do i group duplicate objects in an array

Viewed 6596

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}]
3 Answers

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));
Related