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.



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


Output:

10

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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.

full-stack-img




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.