var data = [ {id:1, qty:100}, {id:2, qty:200}, {id:1, qty:100}, {id:2, qty:200} ];
How to sum this array become to [ {id:1, qty:200}, {id:2, qty:
You can do it by using the functional way, with the .reduce() and .map() method.
In my example, i've made a function to make the process more generic.
var data = [ {id:1, qty:100}, {id:2, qty:200}, {id:1, qty:100}, {id:2, qty:200} ];
function reducer(data, groupBy, reduceValue){
//Reduce your data and initialize it with an empty object
return [].concat.apply(data.reduce(function(hash, current){
//If hash get current key, retrieve it and add sum property
hash[current[groupBy]] = (hash[current[groupBy]] || 0) + current[reduceValue];
//Return our current hash
return hash;
}, {})).map(function(elm){
//Retrieve object keys
return Object.keys(elm).map(function(key){
//Build our object
var obj = {};
obj[groupBy] = +key;
obj[reduceValue] = elm[key];
return obj;
});
})[0];
}
console.log(reducer(data, 'id', 'qty'));
//[ {id:1, qty:200}, {id:2, qty:400} ];
This function takes 3 arguments