VOOZH about

URL: https://www.geeksforgeeks.org/javascript/lodash-_-reduce-method/

⇱ Lodash _.reduce() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lodash _.reduce() Method

Last Updated : 3 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:

  • 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.

Output:

10

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

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.

Comment