Sum all data in array of objects into new array of

2020-05-24 20:47发布

I have an array of objects that looks like this:

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}]

and I want to sum each element in the array to produce an array like this:

var result = [{costOfAirtickets: 4000, costOfHotel: 2200}]

I have used a map and reduce function but I was able to only sum an individual element like so:

data.map(item => ite.costOfAirtickets).reduce((prev, next)=>prev + next); // 22

At the moment this produces a single value which is not what I want as per initial explanation.

Is there a way to do this in Javascript or probably with lodash.

14条回答
Rolldiameter
2楼-- · 2020-05-24 21:12

You could reduce the array by taking an object for summing.

var data = [{ costOfAirtickets: 2500, costOfHotel: 1200 }, { costOfAirtickets: 1500, costOfHotel: 1000 }],
    keys = ['costOfAirtickets', 'costOfHotel'],
    sum = data.reduce((r, o) => {
        keys.forEach(k => r[k] += o[k]);
        return r;
    }, Object.assign(...keys.map(k => ({ [k]: 0 }))));

console.log(sum);

查看更多
smile是对你的礼貌
3楼-- · 2020-05-24 21:13

To create a resultant / reduced value, you should use .reduce() method instead of .map():

let data = [
  {costOfAirtickets: 2500, costOfHotel: 1200},
  {costOfAirtickets: 1500, costOfHotel: 1000}
];

let result = data.reduce(
  (a, c) => (Object.keys(c).forEach(k => (a[k] = (a[k] || 0) + c[k])), a), {}
);

console.log(result);

查看更多
在下西门庆
4楼-- · 2020-05-24 21:18

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];

var result = [data.reduce((acc, n) => {
  for (var prop in n) {
    if (acc[prop]) acc[prop] += n[prop];
    else acc[prop] = n[prop];
  }
  return acc;
}, {})]
console.log(result)

查看更多
一纸荒年 Trace。
5楼-- · 2020-05-24 21:20

My simplistic answer would be like;

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},
            {costOfAirtickets: 1500, costOfHotel: 1000}],
    res  = data.reduce((p,c) => Object.entries(c).reduce((r,[k,v]) => (r[k]+=v, r), p));
console.log(res);

A note on usage of .reduce(): If the array items and the accumulated value is of same type you may consider not using an initial value as an accumulator and do your reducing with previous (p) and current (c) elements. The outer reduce in the above snippet is of this type. However the inner reduce takes an array of key (k) value (v) pair as [k,v] to return an object, hence an initial value (p) is essential.

The result is the accumulated value as an object. If you need it in an array then just put it in an array like [res].

查看更多
够拽才男人
6楼-- · 2020-05-24 21:22

Try using reduce only as in the below snippet. Try avoiding multiple iterations. Hope the below snippet helps!

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}]

var total = data.reduce(function (result,value,key) {
result['costOfAirtickets'] = result['costOfAirtickets']  + value['costOfAirtickets'];
result['costOfHotel'] = result['costOfHotel']  + value['costOfHotel'];

return result},{costOfAirtickets:0,costOfHotel:0});

console.log(total)

查看更多
叼着烟拽天下
7楼-- · 2020-05-24 21:23

map the object and calculate the sum and store it in another.

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
var result = [];
var sum = 0;
var costsum = 0;
data.map(function(item, key){
  var cost = item;
  //nsole.log(cost);
  sum = sum + cost.costOfAirtickets;
  costsum = costsum + cost.costOfHotel;

});

result = [{costOfAirtickets:sum, costOfHotel:costsum}];

console.log(result);

查看更多
登录 后发表回答