Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter, and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Summing an Array of Numbers:
4.2.
JavaScript
4.3.
Concatenating String Elements:
4.4.
JavaScript
4.5.
Reducing to an Object:
4.6.
JavaScript
4.7.
Complex Reduction with Nested Structures:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
How does _.reduce() differ from native JavaScript Array.reduce()?
5.2.
What happens if the accumulator is not provided in _.reduce()?
5.3.
Is _.reduce() efficient for large collections?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.reduce() Method

Author Riya Singh
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Aggregating or accumulating values from a collection is a staple in data manipulation, and Lodash offers a robust solution with its _.reduce() method. This function iteratively applies a function across the elements of a collection, accumulating the results into a single value. 

Lodash _.reduce() Method

This article will delve into _.reduce(), discussing its syntax, usage, and practical applications, complemented by illustrative examples and FAQs.

Why This Function is Used

The _.reduce() function is used for transforming a collection into a single accumulated value. This method is particularly useful in scenarios like summing up values, concatenating strings, or merging objects. It's a cornerstone in functional programming, providing a flexible approach to iterating over a collection and building up a result based on each element.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter, and Return Value

Syntax: 

_.reduce(collection, [iteratee=_.identity], [accumulator])

Parameters:

  • collection (Array|Object): The collection to iterate over.
     
  • [iteratee=_.identity] (Function): The function invoked per iteration.
     
  • [accumulator]: The initial value to start accumulation.

Return Value: 

Returns the accumulated value.

Examples 

Summing an Array of Numbers:

  • JavaScript

JavaScript

var _ = require('lodash');

var numbers = [1, 2, 3, 4, 5];

var sum = _.reduce(numbers, (sum, n) => sum + n, 0);

console.log(sum);

Output: 

15


Demonstrates adding up the numbers in an array.

Concatenating String Elements:

  • JavaScript

JavaScript

var strings = ['hello', 'world', 'lodash'];

var concatenated = _.reduce(strings, (result, str) => result + ' ' + str, '');

console.log(concatenated);

Output:

'hello world lodash'


Shows concatenation of strings in an array.

Reducing to an Object:

  • JavaScript

JavaScript

var keyValuePairs = [['a', 1], ['b', 2], ['c', 3]];

var object = _.reduce(keyValuePairs, (result, [key, value]) => {

 result[key] = value;

 return result;

}, {});

console.log(object);

Output: 

{ 'a': 1, 'b': 2, 'c': 3 }


An example of transforming an array of pairs into an object.

Complex Reduction with Nested Structures:

  • JavaScript

JavaScript

var collections = [{ 'count': 5 }, { 'count': 10 }, { 'count': 15 }];

var totalCount = _.reduce(collections, (sum, obj) => sum + obj.count, 0);

console.log(totalCount);

Output: 

30


Demonstrates summing values from a collection of objects.

Frequently Asked Questions 

How does _.reduce() differ from native JavaScript Array.reduce()?

Lodash's _.reduce() works with arrays, objects, and even strings, providing more flexibility than the native Array.reduce(), which is limited to arrays.

What happens if the accumulator is not provided in _.reduce()?

If an accumulator is not provided, _.reduce() uses the first element of the collection as the initial accumulator and starts iteration from the second element.

Is _.reduce() efficient for large collections?

_.reduce() is efficient for most collections, but its performance depends on the complexity of the iteratee function and the size of the collection.

Conclusion

Lodash's _.reduce() method is a powerful tool for accumulating values from a collection. It provides a streamlined and expressive way to iterate over a collection and combine its elements into a single result, making it indispensable for various data transformation tasks.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.cloneWith() Method
Next article
Lodash _.keyBy() Method
Live masterclass