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: 3200}]


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.

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 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


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, '1')).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.

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);




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})

Another solution would be to use Map (not Array.prototpe.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. {}).

You can use a simple forEach() loop for that:



var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
var res = [];
var tempObj = {};
data.forEach(({costOfAirtickets, costOfHotel}) => {
tempObj['costOfAirtickets'] = (tempObj['costOfAirtickets'] || 0) + costOfAirtickets;
tempObj['costOfHotel'] = (tempObj['costOfHotel'] || 0) + costOfHotel;
});
res.push(tempObj);
console.log(res);




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)




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);




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);






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)




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);


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].

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue