Skip to content Skip to sidebar Skip to footer

Merge Duplicates In Javascript Array

I have a stupid problem that at first seems to be simple to solve, but turns out to be tricky. I have an array of objects, each with two properties: id and value: [ {id: 2, valu

Solution 1:

You can do it like this:

//Assuming:a= [{id:2, value:10}, {id:4, value:3}, {id:2, value:2}, {id:1, value:15}]

varb= {},//Temporaryvariable;c= [];//Thiswillcontaintheresult;//Buildaid:valueobject( {1:15, 2:12, 4:3} )a.map(function(current){b[current.id]=(b[current.id]||0)+current.value});for(varkeyinb){//Formthatintothedesiredoutputformat.c.push({id:parseInt(key,10),value:b[key]});}console.log(c);/* [{id:1, value:15},
    {id:2, value:12},
    {id:4, value:3}]  */

I'm using parseInt(key, 10), since the keys are strings, you'll probably want them converted to integers again.

Solution 2:

// First group the data based on id and sum the valuesvar temp = data.reduce(function(result, current) {
    result[current.id] = (result[current.id] || 0) + current.value;
    return result;
}, {});

// then recreate the objects with proper id and value propertiesvar result = [];
for (var key in temp) {
    result.push({
        id: parseInt(key, 10),
        value: temp[key]
    });
}

console.log(result);

Output

[ { id:1, value:15 },
  { id:2, value:12 },
  { id:4, value:3 } ]

Solution 3:

The quickest approach loops over the array only once using Array.prototype.filter():

var tmp = {},
    result = arr.filter(function (el) {
        if (tmp.hasOwnProperty(el.id)) {
            tmp[el.id].visit += el.visit;
            returnfalse;
        }
        else {
            tmp[el.id] = el;
            returntrue;
        }
    });

It also reuses the objects, though this renders the original array to contain inaccurate values. If this is a problem, you can modify the example to copy each object property to a new object.

Post a Comment for "Merge Duplicates In Javascript Array"