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条回答
老娘就宠你
2楼-- · 2020-05-24 21:02

Here is a lodash approach

_(data).flatMap(_.entries).groupBy(0).mapValues(v=>_.sumBy(v, 1)).value()

It will sum by all the unique keys.

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

var res = _(data).flatMap(_.entries).groupBy(0).mapValues(v=>_.sumBy(v, 0)).value();

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Wrap your result to a [...] or use a .castArray() at the end before unwrapping using .value() in case you want a array as result.

查看更多
该账号已被封号
3楼-- · 2020-05-24 21:03

You don't need to map the array, you're really just reducing things inside it.

const totalCostOfAirTickets: data.reduce((prev, next) => prev + next.costOfAirTickets, 0)
const totalCostOfHotel: data.reduce((prev, next) => prev + next.costOfHotel, 0)
const totals = [{totalCostOfAirTickets, totalCostOfHotel}]

In one go, you could do something like

const totals = data.reduce((prev, next) => { 
    prev.costOfAirTickets += next.costOfAirTickets; 
    prev.costOfHotel += next.costOfHotel; 
}, {costOfAirTickets: 0, costOfHotel: 0})
查看更多
Fickle 薄情
4楼-- · 2020-05-24 21:05

Lodash

Using lodash reduce and _.mergeWith this is a one liner:

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

var result = _.reduce(data, (r,c) => _.mergeWith(r, c, (o = 0, s) => o + s), {})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

ES6 Only

If you do NOT want to mutate the original array you can utilize ES6 reduce, Object.entries, and forEach like this:

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

// One liner
var result1 = data.reduce((r, c) =>
  !Object.entries(c).forEach(([key, value]) => r[key] = (r[key] || 0) + value) && r, {})

// More readable
var result2 = data.reduce((r, c) => {
  Object.entries(c).forEach(([key, value]) => r[key] = (r[key] || 0) + value)
  return r
}, {})

console.log(result1)
console.log(result2)

If we do not care about mutating the initial data array then we can have a one liner solution:

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

data.reduce((r, c) => !Object.entries(c).forEach(([key,value]) => r[key] += value) && r)

console.log(data[0])

More readable:

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

data.reduce((r, c) => {
  Object.entries(c).forEach(([key, value]) => r[key] += value)
  return r
})

console.log(data[0])

The only difference between the mutating and not mutating examples is the initial value for the reduce (and also the fact that with the mutating we use the 0 index to as an accumulator for the sums). In the mutating ones there is no initial value where in the others we start with empty object literal.

if you need the result to be an array specifically then return [data] for the mutating examples and [result] for the pure examples.

查看更多
forever°为你锁心
5楼-- · 2020-05-24 21:06

Another solution would be to use Map (not Array.prototype.map) as it has several notable differences compared to objects:

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

let sums = data.reduce((collection,rcd)=>{
  Object.entries(rcd).forEach(([key,value])=>{
      let sum = collection.get(key) || 0
      collection.set(key, sum + +value)
  })
  return collection
}, new Map())

console.log(...sums.entries())

Explanation

Outer loop

The above first iterates over your data array using the reduce method. Each object within that I'll be referring to as a record -- distinguished in the code via the variable, rcd.

Each iteration of reduce returns a value which is passed as the first argument to the next iteration of the loop. In this case, the parameter collection holds that argument, which is your set of sums.

Inner loop

Within the reduce loop, each key/value pair of the record is iterated over using forEach. To get the key/value pair the Object.entries method is used. Using array destructuring these arguments can be directly assigned to the respective variables, key and value

Retrieving/Setting values

Unlike a primitive object, Map has its own methods for getting and setting its entries using get() and set(). So first retrieve the previous sum using get(), if it's not set then default to 0, which is what the || 0 does. At that point, you can assume the previous sum is at least 0 or greater and add the current key's value onto it.

Alternatives to Map

If you find Map is a bit heavy-handed, you may also use a similar object such as Set, which has many of the same methods (except the get()), or you could also use a primitive object (i.e. {}).

查看更多
姐就是有狂的资本
6楼-- · 2020-05-24 21:06

This is the easiest approach I could think off

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
var sum ={};
for(var obj in data){
  for(var ele in data[obj]){
    if(!data[obj].hasOwnProperty(ele)) continue;
      if(sum[ele] === undefined){
        sum[ele] = data[obj][ele];
      }else{
        sum[ele] = sum[ele] + data[obj][ele];
      }
  }

}
var arr = [sum];
console.log(arr);
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2020-05-24 21:07

Use Lodash to simplify your life.

const _ = require('lodash')
let keys = ['costOfAirtickets', 'costOfHotel']; 
let results = _.zipObject(keys, keys.map(key => _.sum( _.map(data, key))))
...
{ costOfAirtickets: 4000, costOfHotel: 2200 }

Explanation:

  • _.sum(_.map(data, key)): generates sum of each array
  • _.zipObject: zips the results with the array sum
  • using keys.map() for sum of each key as _.map does not guarantee order.

Documentation:

查看更多
登录 后发表回答