Sum the same object of array

2020-04-23 07:20发布

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.

标签: javascript
4条回答
相关推荐>>
2楼-- · 2020-04-23 07:25

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

查看更多
Animai°情兽
3楼-- · 2020-04-23 07:39

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

http://jsfiddle.net/4496escu/2/

查看更多
▲ chillily
4楼-- · 2020-04-23 07:43

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;
查看更多
祖国的老花朵
5楼-- · 2020-04-23 07:47

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

  • the data which will be reduced
  • the groupBy parameter
  • the key of the object to sum data
查看更多
登录 后发表回答