Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 16, 2021 06:45 pm GMT

Demystifying Array.prototype.reduce()

Array.prototype.reduce()

The reduce() method is considered by some Javascript beginners to be the most confusing array iterator. In this tutorial I will present the method in a way that is easily understood, so you can start experimenting with reduce() in your own code. We'll start by taking a macroscopic view of the method, then break it down into digestible bite-sized chunks to understand how each individual part works.

Description

The reduce() method is an Array iterator that executes a "reducer" callback function on each element of the array. The "reducer" callback function must return a single value for use in the next callback method on each subsequent array element.

Returns

After reduce() iterates over the final array element, the method returns the result of the final "reducer" callback function executed.

I personally interpret that the method is called reduce because it will iterate over each individual element of an array, but ultimately the method only returns one value after traversing the entire array.

Destructive?

The reduce() method itself does not directly mutate the array it is called on, so it is not considered a destructive method. However, it's important to note that the callback function might call destructive methods that could mutate the original array.

Syntax

The syntax of the reduce() function itself is very simple:

const numbers = [1, 2, 3];numbers.reduce(callbackFn, initialValue);

Note: The second parameter, initialValue, is optional and not required for the function to run.

As you can see from above, the syntax to implement reduce() is not confusing at all. This is because the complexity of using reduce() comes from the requirements of the "reducer" callbackFn that is passed into the method. So let's break down the syntax of the callback function now.

Here is an example "reducer" callback function that will sum all elements of an array:

const reducer = function(accumulator, currentElement) {  return accumulator + currentElement;}

Note: Similar to other array iterators, it is possible to pass two additional parameters to the callback function. The 3rd parameter passed represents the current index of the array, and the 4th parameter represents the array being traversed.

Here's how each element works:

  • accumulator: This parameter "accumulates" the results of each execution of the callback function. The value that is returned by the preceding callback function becomes the accumulator value in each execution of the callback function.

Note: By default if no initialValue is passed in the reduce() function, then accumulator is initially set to equal the first element of the array.

  • currentElement: This parameter represents the value of the current array element that is being iterated over.

Still confused?

Not to worry, let's go into a simple example together and I'll explain how all of these moving pieces work together in the reduce() method.

Example Breakdown

The most basic implementation of reduce() is to return the sum of all the elements in an array. To start, let's sum up the following odd numbers.

const numbers = [1, 3, 5, 7];const reducer = function(accumulator, currentElement) {  return accumulator + currentElement;}console.log(numbers.reduce(reducer));

This code snippet will "reduce" the array of numbers into a single number by adding them together. The expected result is 16 because 1 + 3 + 5 + 7 = 16.

Let's break this example down to make it more simple.

  • To start, we call reduce on the numbers array and we pass in the callback function reducer as a parameter into reduce.
  • We did not pass the 2nd optional parameter, initialValue, into the reduce() function. So for the first execution of reducer the accumulator is set to the value of the first element in the array and currentElement is set to the value of the second element in the array.

Here's what the first call of reduce() looks like with the reducer callback parameters replaced with array elements:

reducer(numbers[0], numbers[1]) {  return numbers[0] + numbers[1];}

Now written with the values in place of the parameters:

reducer(1, 3) {  return 1 + 3;}

After the initial call of the reducer callback function, reduce() iterates to the next array element executing the reducer callback function over and over until it reaches the end of the array.

Here's a breakdown of the next call of the reducer callback function. This time accumulator is set to equal the returned result of the previous callback function.

reducer(4, numbers[2]) {  return 4 + numbers[2];}

Now written with the values in place of the parameters:

reducer(4, 5) {  return 4 + 5;}

Are you getting the pattern yet? The accumulator simply accumulates the result of the previous callback function and uses it in the next execution of the callback. So for our final call of the example, the accumulator will be equal to 9 as that is the returned value of the previous callback function.

reducer(9, numbers[3]) {  return 9 + numbers[3];}

Now written with the values in place of the parameters:

reducer(9, 7) {  return 9 + 7;}

This was the final call of the reducer callback function because we have now iterated over each array element, so 16 will be the value returned from the original reduce function called on the numbers array.

Other Uses of reduce()

As you saw from the example above, reduce() is very effective at returning the sum of all elements in an array. You might be wondering what other practical uses exist for reduce(). Here are a few:

  • Sum values in an object array
  • Flatten an array of arrays
  • Replace .filter().map() with .reduce()
  • And more!

Challenge

Want more practice? Try to code the following challenge:

Using reduce(), write an implementation that will return the sum of all even numbers in an array. Hint: You must use a conditional statement in your callback function.

Original Link: https://dev.to/pace0033/demystifying-arrayprototypereduce-1hj8

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To