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.
You could reduce the array by taking an object for summing.
To create a resultant / reduced value, you should use
.reduce()
method instead of.map()
:My simplistic answer would be like;
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]
.Try using reduce only as in the below snippet. Try avoiding multiple iterations. Hope the below snippet helps!
map
the object and calculate the sum and store it in another.