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.
The array_sum() function returns the sum of all the values in the array.
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."
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)
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 sumkeys.map()
for sum of each key as _.map
does not guarantee order.Documentation:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With