Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum all data in array of objects into new array of objects

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 => item.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.

like image 530
Dave Kalu Avatar asked Sep 24 '18 12:09

Dave Kalu


People also ask

How do you sum all data in an array?

The array_sum() function returns the sum of all the values in the array.

How do you add elements in array of objects in JS?

The unshift() function is one more built-in array method of JavaScript. It is used to add the objects or elements in the array. Unlike the push() method, it adds the elements at the beginning of the array. "Note that you can add any number of elements in an array using the unshift() method."


2 Answers

Using for..in to iterate object and reduce to iterate array

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];    var result = [data.reduce((acc, n) => {    for (var prop in n) {      if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];      else acc[prop] = n[prop];    }    return acc;  }, {})]  console.log(result)
like image 182
Chris Li Avatar answered Sep 21 '22 08:09

Chris Li


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:

  • sum: https://lodash.com/docs/4.17.10#sum
  • zipObject: https://lodash.com/docs/4.17.10#zipObject
  • map: https://lodash.com/docs/4.17.10#map
like image 26
Roopak A Nelliat Avatar answered Sep 20 '22 08:09

Roopak A Nelliat