How to get the sum of keys of an array of objects in underscore.js?

I have the following array:

var items = [ {price1: 100, price2: 200, price3: 150}, {price1: 10, price2: 50}, {price1: 20, price2: 20, price3: 13}, ] 

I need to get an object with the sum of all the keys, as shown below:

 var result = {price1: 130, price2: 270, price3: 163}; 

I know that I can only use a loop, but I'm looking for an underline style approach :)

+6
source share
3 answers

Not very pretty, but I think the fastest way is to do it like this.

 _(items).reduce(function(acc, obj) { _(obj).each(function(value, key) { acc[key] = (acc[key] ? acc[key] : 0) + value }); return acc; }, {}); 

Or, to go really on top (I think it will be faster than higher if you use lazy.js instead of underscore):

 _(items).chain() .map(function(it) { return _(it).pairs() }) .flatten(true) .groupBy("0") // groups by the first index of the nested arrays .map(function(v, k) { return [k, _(v).reduce(function(acc, v) { return acc + v[1] }, 0)] }) .object() .value() 
+5
source

For aggregation, I would recommend reduce :

 _.reduce(items, function(acc, o) { for (var p in acc) acc[p] += o[p] || 0; return acc; }, {price1:0, price2:0, price3:0}); 

Or better

 _.reduce(items, function(acc, o) { for (var p in o) acc[p] = (p in acc ? acc[p] : 0) + o[p]; return acc; }, {}); 
+1
source

Js from hell:

 var names = _.chain(items).map(function(n) { return _.keys(n); }).flatten().unique().value(); console.log(_.map(names, function(n) { return n + ': ' + eval((_.chain(items).pluck(n).compact().value()).join('+')); }).join(', ')); 

jsfiddle

0
source

Source: https://habr.com/ru/post/948262/


All Articles