Last Updated : 03 Sep, 2024
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:
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4