Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js: Sum of items in a collection

I made a small plnkr here to show what I am trying to achieve. I have a big dataset, where I like to sum the individual type to get a total.

I could think of iterating and adding the results to an object hash, but wonder more elegant way to solve it with underscore. I am using underscore.js, but never tried map reduce or other functional paradigm. Please update the plnkr to learn how to do this.

http://plnkr.co/edit/B5HGxhwvWsfvOR97z7TL?p=preview

var data = [ {'type': "A", 'val':2},
  {'type': "B", 'val':3},
  {'type': "A", 'val':1},
  {'type': "C", 'val':5} ];


 _.each(data, function (elm, index) {
   console.log(elm);  
 });

 /*
 Desired output

 out = [ {'type': "A", 'total':3},
  {'type': "B", 'total':3},
  {'type': "C", 'total':5} ];

 */
like image 943
bsr Avatar asked Jan 20 '13 23:01

bsr


People also ask

Is underscore JS still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

How do you use underscore in JavaScript?

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

What is _ each in JavaScript?

The _.each function accepts an array or an object, an iteratee function and an optional context object, the iteratee function is invoked once and in order for each array item The iteratee function provides 3 arguments item - The current iterated object (or value if an object was passed) i - The index of the iterated ...

Why is JavaScript underscore better?

It provides utility functions for a variety of use cases in our day-to-day common programming tasks. Underscore. js provides a lot of features that make our task easy to work with objects. It can be used directly inside a browser and also with Node.


1 Answers

var data = [ { type: "A", val: 2 },
             { type: "B", val: 3 },
             { type: "A", val: 1 },
             { type: "C", val: 5 } ];

var groups = _(data).groupBy('type');

var out = _(groups).map(function(g, key) {
  return { type: key, 
           val: _(g).reduce(function(m,x) { return m + x.val; }, 0) };
});

DEMO

like image 132
Sergey Berezovskiy Avatar answered Nov 01 '22 21:11

Sergey Berezovskiy