Sum the same object of array

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

提交回复
热议问题