Edison Neo
Edison Neo

Reputation: 53

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

Upvotes: 5

Views: 9526

Answers (3)

user3637352
user3637352

Reputation: 31

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

Upvotes: 2

adeneo
adeneo

Reputation: 318222

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)

Upvotes: 9

Jonas Wilms
Jonas Wilms

Reputation: 138277

var array= [
 {id: 0, weight: 200},
 {id: 0, weight: 200},
 {id: 1, weight: 75},
 {id: 2, weight: 5}];

console.log(array.reduce((function(hash){
return function(array,obj){
 if(!hash[obj.id])
  array.push(hash[obj.id]={id:obj.id,times:1});
 else
   hash[obj.id].times++;
  return array;
  };    
})({}),[]));

See Combine multiple arrays by same key for an explanation and you can try it here :http://jsbin.com/licuwadifa/edit?console.

Upvotes: 1

Related Questions