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.