Sum The Same Object Of Array
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:400} ]; Thx.
Solution 1:
Try this:
var sum = [];
data.forEach(function(o) {
var existing = sum.filter(function(i) { return i.id === o.id })[0];
if (!existing)
sum.push(o);
else
existing.qty += o.qty;
});
See Fiddle
Solution 2:
With Ramda
:
var f = R.compose(
R.values(),
R.mapObj(R.reduce(function(a,b) {return {'id': b.id, 'qty':a.qty+b.qty}}, {qty:0})),
R.groupBy(R.prop('id'))
);
var data = [ {id:1, qty:100}, {id:2, qty:200}, {id:1, qty:100}, {id:2, qty:200} ];
console.log(f(data));
Solution 3:
I didn't get to run this on any data, but the logic seems right. Basically this code goes through your array, and for each unique instance it will store the values into a temporary array and the write over the original array with the results.
var temp = [];
temp.push(data[0])
for (x = 1; x < data.length; x++){
for (i = 0; i < temp.length; i++){
if (temp[i].id != data[x].id && temp[i].qty != data[x].qty ){
temp.push[data[x]];
}
}
}
data = temp;
Solution 4:
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} ];
functionreducer(data, groupBy, reduceValue){
//Reduce your data and initialize it with an empty objectreturn [].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 hashreturn hash;
}, {})).map(function(elm){
//Retrieve object keysreturnObject.keys(elm).map(function(key){
//Build our objectvar 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
- the data which will be reduced
- the groupBy parameter
- the key of the object to sum data
Post a Comment for "Sum The Same Object Of Array"