Sum the same object of array

前端 未结 4 703
[愿得一人]
[愿得一人] 2021-01-25 09:09
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:

相关标签:
4条回答
  • 2021-01-25 09:31

    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/

    0 讨论(0)
  • 2021-01-25 09: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;
    
    0 讨论(0)
  • 2021-01-25 09:54

    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

    0 讨论(0)
  • 2021-01-25 09:56

    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
    0 讨论(0)
提交回复
热议问题