Sum the same object of array

前端 未结 4 707
[愿得一人]
[愿得一人] 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: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

提交回复
热议问题