JavaScript Array reduce() method – How it works

JavaScript Array reduce() method – How it works

It is quite known that Javascript arrays are one of the most powerful and comprehensive tools that can be used for almost anything. They have some special functions like reduce method to help you easily work with their data.

This tutorial will teach you about a very uncommon but very useful method known as the Javascript Array reduce() method. Let’s get started!

Prerequisites

Here are some prerequisites to be aware of before we get started:

  • Javascript is written in ES6 using shorthand arrow functions and one-liners.
  • The use of Javascript arrays and callbacks is generally understood.

What is Array Reduce()?

Arr.reduce() performs a reducer function on each element of the array and returns a single output.

The reducer runs through all array elements (from left to right) in order and returns the result from the calculation on the preceding element. Thus, the final result is a single value.

The simplest use of reduce() is when we want the sum of all elements of an array.

const elements = [10, 20, 30, 40];
const sum = elements.reduce((currSum, ele) => currSum + ele);
console.log(sum);
//Output - 100 Code language: JavaScript (javascript)

The array element at index 0 is used as the initial value and iteration starts from the next element when the callback runs for the first time.

Syntax

array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue)Code language: PHP (php)
  • function(accumulator, currentValue, currentIndex, arr) : This is the callback function executed on each element of the array. It can take up to 4 parameters:
    1. accumulator (required): Callback’s returned values are accumulated in this parameter.
    2. currentValue (required): Stores the current element value.
    3. currentIndex (optional): Stores the current element index.
    4. arr (optional): Contains the currently traversed array.
  • initialValue (optional): This is the value that will be passed to the function on the first call. In absence of this parameter, the first element will work as the accumulator and the second value in the array is initialized as currentValue.

Take a look at some of the ways you can call the reduce() method.

//using Arrow functions
const ans = arr.reduce((total, currentValue) => { /* … */ } )
const ans = arr.reduce((total, currentValue, currentIndex) => { /* … */ } )
const ans = arr.reduce((total, currentValue) => { /* … */ } , initialValue)Code language: JavaScript (javascript)
//using Callback Functions
function callbackFn(total, currentValue) { /* … */ }
const ans = arr.reduce(callbackFn)
const ans = arr.reduce(callbackFn, initialValue)Code language: JavaScript (javascript)
//using Inline callback function
const ans = arr.reduce(function(total, currentValue) { /* … */ })
const ans = arr.reduce(function(total, currentValue) { /* … */ }, initialValue)Code language: JavaScript (javascript)

Return Value

It returns a single value after running the reducer function over the entire array to completion.

But there’s an exception to that. it will give an error when the array contains no elements or no initialValue is provided.

TypeError: Reduce on an empty array with no initial value

Examples of Reduce method

Enough of theory, lets drive jump into some real-life usages of this amazing function.

1. To get the sum of all values in an Array

Using a reducer to get the sum of all elements in an array

2. To eliminate duplicates from an Array

Using reducer to eliminate duplicates from an array

Now, let’s look at some advanced techniques with reduce() method.

3. To showcase the elements along with their count in an array

reduce() method can be used if we are trying to count the number of each item in a collection.

Method to convert the elements to their occurrence key-value object

4. To use reduce() in place of filter() and map()

In some cases, we need to filter and then map data. It generally makes us traverse the same array twice. reduce() helps us achieve the same thing by traversing the same array only once.

Finding and returning only odd numbers in the array multiplied by 2

Behavior during array mutations

Here are some possible scenarios of array mutations during a reduce() call and how reduce() behaves in this situation:

  • reduce() does not visit the array elements that were supposed to be iterated but got deleted after reduce() began. Eg:
let arr = [1, 2, 3, 4];

arr.reduce((result, currElement, currIdx, originalArr) => {
  originalArr.pop();
}, []);

console.log(arr); //[1, 2]

// Explanation: Because the 3rd and 4th elements were removed during previous calls, the function is executed only twice on the first two elements. Thus, resulting in [1, 2] as the final array.Code language: JavaScript (javascript)
  • Similarly, The callback function does not iterate over the elements added to the array after the reduce() begins.
let arr = [1, 2];

arr.reduce((result, currElement, currIdx, originalArr) => {
  originalArr.push(5);
}, []);

console.log(arr); //[1, 2, 5, 5]

// Explanation: The reduce function only gets called on the initial elements [1, 2] and adds 5 to the original array each time.Code language: JavaScript (javascript)

Some Points to Remember

  • reduce() itself does not modify the array it is used on, however, code inside the callback function can do so as we saw in the above section.
  • The same value will be returned without calling the callback function if either there is only one element in the array without initialValue or the array is empty but initialValue is provided.
  • An error will be thrown if the array provided is empty and no initialValue is given.
  • Even if the elements do get changed after the calling, values passed to the callback function will remain the same as they were during the first reduce() call.
  • In Javascript, recursive functions reduce() are powerful but sometimes tricky to understand, especially for people with less experience. While the code becomes easier to read with other array methods, reduce() should be considered an option with other advantages it offers.

Conclusion

While we just learned how to use reduce() in javascript arrays, Javascript arrays have a lot more to offer. One similar function is reduceRight() which works the same way as reduce(). The only difference comes in the direction of the iteration i.e reduce() iterates over the array elements from left to right while reduceRight() iterates from right to left.

If you ever feel lost and want help understanding where to start your coding journey then go check out Codedamn. There are amazing courses and blogs for web development and other coding concepts. Remember to practice coding on a daily basis. You can play around with your code on Codedamn’s online compiler as well

Let us know in the comments if you have any suggestions or queries. Finally, If you are interested in my content and would like to connect, then you can find me on Linkedin or Twitter.

Thank You for reading!

Sharing is caring

Did you like what Indrakant wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far