Skip to content
Related Articles

Related Articles

Lodash _.groupBy() Method
  • Last Updated : 02 Sep, 2020

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.

The _.groupBy() method creates an object composed of keys generated from the results of running each element of collection through the iteratee function. The order of the grouped values is determined by the order they occur in the collection. Also the corresponding value of each key is an array of elements responsible for generating the key.

Syntax:

_.groupBy( collection, iteratee )

Parameters: This method accepts two parameters as mentioned above and described below:

  • collection: It is the collection that the method iterates over.
  • iteratee: It is the function that is invoked for every element in the array.

Return Value: This method returns the composed aggregate object.



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var users = ([6.5, 4.12, 6.8, 5.4]);
  
// Using the _.groupBy() method
let grouped_data = _.groupBy(users, Math.floor )
  
console.log(grouped_data);

chevron_right


Output:

{ '4': [ 4.12 ], '5': [ 5.4 ], '6':[ 6.5, 6.8 ] }

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var users = (['eight', 'nine', 'four', 'seven']);
   
// Using of _.groupBy() method
// with the `_.property` iteratee shorthand 
let grouped_data = _.groupBy(users, 'length')
  
console.log(grouped_data);

chevron_right


Output:

{ '4': [ 'nine', 'four' ], '5': [ 'eight', 'seven' ]}

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var users = (['one', 'two', 'three', 'four']);
var obj = ([ 3.1, 1.2, 3.3 ]);
   
// Using the _.groupBy() method
// with the `_.property` iteratee shorthand 
let grouped_data = _.groupBy(users, 'length')
let grouped_data2 = _.groupBy(obj, Math.floor)
  
// Printing the output 
console.log(grouped_data, grouped_data2);

chevron_right


Output:

{ '3': [ 'one', 'two' ], '4': [ 'four' ], '5': [ 'three' ] } 
{ '1': [ 1.2 ], '3': [ 3.1, 3.3 ] }

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :