Underscore.JS - groupBy method



Syntax

_.groupBy(list, iteratee, [context])

groupBy method gets the spilted lists grouped by running the iteratee method provided.

Example

var _ = require('underscore');

var list = ["Sam", "Joe", "Julie", "Aleen"]

//Example 1. invoke groupBy method to get grouped list by length
var result = _.groupBy(list, 'length');
console.log(result);

list = [1.3, 1.2, 1.5, 2.4, 2.3, 2.5]

//Example 2. invoke groupBy method to get grouped list of number
result = _.groupBy(list, function(num){ return Math.floor(num); })
console.log(result)

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

{ '3': [ 'Sam', 'Joe' ], '5': [ 'Julie', 'Aleen' ] }
{ '1': [ 1.3, 1.2, 1.5 ], '2': [ 2.4, 2.3, 2.5 ] }
underscorejs_processing_collection.htm
Advertisements