Array methods: The reduce array method and chaining multiple array methods

Simeon Kengere
3 min readJul 22, 2022

--

In this article, we will look at the reduce array method, and perform chaining of this method and the filter method. Click here to have a look at the filter array method in case you are unfamiliar with it.

We use the reduce method to narrow down all the elements of an array to one single value. For example, we might want to find the sum of all the elements in an array.

Consider the following array:

The parameters accepted by the reduce array method are: the accumulator, element, index, and the array itself in that order. The accumulator accumulates the callback’s return values. It is important to note that the accumulator needs to have an initial value, which is declared outside the body of the function.

Let us have a look at how we should pass in those 4 parameters, in addition to calculating the sum of all the elements in the array:

In the example above, we want to start counting from 0, so the value of the accumulator is set to 0.

The following will be the output on the console:

The following is the result of the return value of the reduce method on the console:

Indeed, when you add all the elements of the array myNumbers, you get the total as 1035.

Now, you might be wondering why would you choose this method over the for loop? Let us start by writing a for loop to calculate the sum of all elements in our myNumbers array.

And the output on the console would be:

You can notice that with the for loop, we need an external variable (count) as opposed to the reduce method. That is fine if you are working with one loop, but it can get very messy if we are working with multiple loops for performing multiple operations. The array methods completely avoid the extra variable (count) when working on multiple loops that perform different operations.

Now having covered the reduce array method, let us perform chaining of both the filter and the reduce array method.

Let us say that from our array (myNumbers), we want to find the sum of all positive numbers in the array. The following is how we would do it:

The output on the console would be:

Indeed, when you add all the positive numbers of the array myNumbers, you get the total as 1285.

--

--