Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i group duplicate objects in an array

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}]
like image 513
Edison Neo Avatar asked Dec 24 '22 16:12

Edison Neo


2 Answers

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)
like image 96
adeneo Avatar answered Dec 28 '22 09:12

adeneo


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));
like image 30
user3637352 Avatar answered Dec 28 '22 10:12

user3637352