Open In App

Lodash _.reduce() Method

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash's _.reduce() method iterates over a collection, applying an iterative function to each element to accumulate a single value. The method starts with an initial value or the first element if no accumulator is provided, progressively reducing the collection.

Syntax

_.reduce(collection, iteratee, accumulator)

Parameters:

This method accepts three parameters as mentioned above and described below:

  • collection: This parameter holds the collection to iterate over.
  • iterate: This parameter holds the function invoked per iteration.
  • accumulator: This parameter holds the initial value.

Return Value: This method returns the accumulated value.

Example 1: In this example we use Lodash's _.reduce() method to sum the elements in the users array, starting from 0. The result is 10.

javascript
// Requiring the lodash library 
const _ = require("lodash"); 
     
// Original array 
let users = [ 1, 2, 3, 4 ];
 
// Use of _.reduce() method
 
let gfg = _.reduce(users, function(sum, n) {
  return sum + n;
}, 0);

// Printing the output 
console.log(gfg);

Output:

10

Example 2: In this example we use Lodash's _.reduce() method to group object keys (users) by their values.

javascript
// Requiring the lodash library 
const _ = require("lodash"); 
     
// Original array 
let users = { 'p': 2, 'q': 3, 'r':2, 's': 2  }
 
// Use of _.reduce() method
 
let gfg = _.reduce(users, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
  return result;
}, {});

// Printing the output 
console.log(gfg);

Output:

{ '2': ['p', 'r', 's'], '3': ['q'] }

Note:

This code will not work in normal JavaScript because it requires the library lodash to be installed.


Similar Reads