Thursday, October 23, 2025
HomeLanguagesJavascriptLodash _.reduce() Method

Lodash _.reduce() Method

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 _.reduce() method reduces collection to value which is accumulated result of running each element in the collection through iteratee, where each successive invocation is supplied return value of the previous. The first element of the collection is used as the initial value, if accumulator is not given. There are many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform.

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.
  • iteratee: 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: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.




// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var 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:




// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var 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.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS