Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sum of an array object keys 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 object with sum of all keys like the following:

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

I know I may to use just loop but I'm looking for a approach in underscore style :)

like image 1000
Erik Avatar asked Jun 27 '13 18:06

Erik


People also ask

How do you find the sum of an array of objects?

To sum a property in an array of objects:Call the reduce() method to iterate over the array. On each iteration increment the sum with the specific value. The result will contain the sum of the values for the specific property.

What is _ each in JavaScript?

Collection Functions (Arrays or Objects) each _.each(list, iteratee, [context]) Alias: forEach. Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed.

How do you use underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.


1 Answers

Not very pretty, but I think the fastest method 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 over the top (I think it will can be faster than above one, 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()
like image 79
Artur Nowak Avatar answered Oct 03 '22 13:10

Artur Nowak