Ere now I believe most of us have not even heard of the array method called the Array.reduce method. Well, coming to that in a splash.While on this course we will likely be seeing more of the Es6 methods.

What is Array.reduce method: This is a method used to access the values of an array. It loops through the values of an array one time and returns a single value. Array.reduce method also takes parameters in its function, it takes up to 4 parameters which will be shown just in some seconds.

The Array.reduce method seems to be the most powerful array method I have encountered as a javascript developer. I hope we are ready for its time to get the feel and we will see how powerful this method is.
Array.reduce method has syntax to which is been used upon, this syntax will be shown below.


Remember I told us that this method takes up to four parameters and we are going to implement it to the syntax we have above in the below example

Array.reduce(wrapper, current values, current index, array)

Above is the way to implement the parameters that we had discussed previously.

The First value represents the wrapper to which all other values are submissive to, it holds the returns of the current values each time iteration takes on each value of an array and returns the final result after the callback function has been executed.

It also represents the first value of an array. Iterations of the Array.reduce method always starts from the left to the right until it reaches the last value of the array.

The second parameter is the current value at each iteration until the loops finish.

The third parameter takes the current index of the values at each looping process until it reaches the last value.

The fourth parameter takes the replica of the array at each iteration.
This is the four-parameter and the roles they play. We have one last one which is a strong bone to these parameters, it’s called the initial value. Array.reduce implies that the initial value has a great role to play in the iteration process.

The initial-value comes just after the callback function of the Array.reduce method, below is an illustration on that;

(callback fn (Wrapper, currentValue, currentIndex, Array) => things to return, initialValue)

This is what happened in the above illustration, inside the callback function holds the parameters and after the arrow function which calls for our return value, you add a comma(,) and add the initial value. The initial-value varies from numbers, strings, array, object and so on.

Now, let us look at the applications of this method before proceeding further. We will be using this method to take the sum-product of an array that holds numbers as its values.

const sumNum = (…array) => {
let result = array.reduce(
(wrapper, currentValues, currentIndex, copyArray) =>
wrapper + currentValues,
return result;
console.log(sumNum(1, 2, 3, 4, 5));//15

This above function returns the sum-product of the array values. How do this works;

1 + 2 + 3 + 4 + 5 //15

Glancing at the function, we used the rest operator to have access to the incoming values of the array which enable us to pass the values of the array as so in our arguments without enclosing it in a square brace like so [1,2,3,4,5].

Looking at the function parameters the wrapper as we mentioned above holds the current sum-product at each iteration and finally returns the sum-product of all the values for us.

Let have a quick sketch on that;

Before the loop start, the wrapper takes the initial value which we declared to be zero;

wrapper = 0, currentValue = 1 first iteration currentValue = 1, wrapper = 0// 0 + 1=> 1 second iteration currentValue = 2 ,wrapper = 1// 1 + 2 => 3//  third iteration currentValue = 3 ,wrapper = 3// 3 + 3 => 6 fourth iteration currentValue = 4 ,wrapper = 6// 6 + 4 => 10 fifth iteration currentValue = 5 ,wrapper = 10//10 + 5 => 15

Let us see clearly how the initial values affect the sum-product in the example below:

const sum-product = (…array) => { let result = array.reduce( (wrapper, currentValues, currentIndex, copyArray) =>
wrapper + currentValues,
return result;};console.log(sum-product(1, 2, 3, 4, 5));//17

In the above function, instead of the wrapper being 15 is now 17. Why? Because we have set the initial value to be 2, by so doing we are making the starting point to be 2.

Let get things here; the normal count of the array values is 15 because we have added 2 as our initial value, instead of the wrapper to start from 0 it checks, if there is any initial value declared, in this case, is yes, and because is yes the wrapper now wraps the initial value, making the wrapper to be 2 before the loops start.

Moreso, talking of the parameters, we have seen that all the parameters we passed were not returned. Yes, it simply means that all the parameters are not required. The wrapper and the current value are always required. Let print all those parameters to our console and see what the parameters hold at each iteration.

const sumNum = (…array) => { array.reduce((wrapper, currentValues, currentIndex, copyArray) => { wrapper + currentValues; console.log(wrapper); console.log(currentValues); console.log(currentIndex); console.log(array);
}, 0);
SumNum(1, 2, 3, 4, 5);0
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

This shows us what was happening behind the scene as the iterations were taken place. All the parameters are printed out to the console according to the steps at each iteration.

The wrapper is 0 before the iteration as we can see, current-value is 1, current-index is 0 and the array is always the copy of the original array, this process is taken place while the iteration keeps going.

Is this not beautiful, yes it is! Unlike the other types of array reduce is the only method that makes this very easy and neat. Let us take a look at just two methods amongst many of the array methods and see how this can be also achieved.
We will be looking at the Array.map and Array.forEach method of an array.
First, let see the map method:

const sumNum = (…array) => {
let count = 0;
let result = array.map(nums => (count += nums));
console.log(result);// [ 1, 3, 6, 10, 15 ],
console.log(count)// 15
sumNum(1, 2, 3, 4, 5);

Looking at the above example, we have successfully achieved the same sum-product of the array values with the map method, another powerful array method too.

When we print the result to the console it returns the current sum-product at each iteration in an array, this is because the map returns an array of its result and believes one of the array methods I have seen that can convert the string number values of an array to an integer with Array.reduce method.

When will print the count to the console we received the total count itself which the wrapper was given us without having the count or declare any other variable differently to hold the sum-product.

Now let see how the Array.forEach method will give us the sum-products of the values of an array;

const sumNum = (…array) => { let count = 0; array.forEach(nums => (count += nums)); console.log(count);}sumNum(1, 2, 3, 4, 5);

This seems to be the same way the Array.map method was returning the sum-products of the array values above but just that it was not returning an array of its result.

Accept it when I tell you that this is also very powerful on its own. The forEach method is a method that calls the callback function one time for all the values of the array, it does not take a variable, unlike the other array methods.

There are things to consider always whenever we are to use the array method called Array.reduce method, those are;

1. The wrapper and the current-value parameters are always required;

2. It can always take up to four parameters

3. The wrapper is always the first value of an array if the initial-value is not declared

4. The current-value is always the last value of an array when the initial value is not declared.

5. Whenever the initial-value is declared the wrapper holds the initial-value that is declared.

Let us have more examples of what we can use the Array.reduce method to archive in our code.

Now we will be using the Array.reduce method to get the first and last value of an array; believe me, countless programmers have not known that the Array.reduce method can provide us with such.

Many failed interview questions because of not knowing the appropriate array method to apply at a given task. Nevertheless, many hidden tricks will be clear to us all.

const findFirstValueOfAnArray = (…array) => { let result = array.reduce((a, b) => a); console.log(result);//1};findFirstValueOfAnArray(1, 2, 3, 4, 5);

This function gave us the first value of the array which is 1. Remember we talked about the wrapper being the first value of the array if the initial-value is not assigned a value. that is what just happened here.

const findLastValueOfAnArray = (…array) => { let result = array.reduce((wrapper, currentValue) => b); console.log(result);// 5};
findValueOfAnArray(1, 2, 3, 4, 5);

Here the same thing is applied to the current-value but whether the initial value is declared or not declared the current value will always print the last value of the array.

Let us again use the Array.reduce method, to sum up, the object value of an array of objects.:

const addingObjectValues = arrOfObjects => { return arr.reduce((wrapper, currentValue) => wrapper+ currentValue.item),0);};console.log(addingObjectValues([{ item: 1 }, { item: 2 }, { item: 3 }]));//6

what just happened? thoughts of our mind right now, but relax I promise there won’t be any confusion on this one.

Let us remember our normal way of accessing object values.

To know more on object click on this object model link

Because our arguments is an array, we mapped through the array and got the object values with there keys.

If we look closely we will see that currently what our current value was having is the object, as its values are objects, with the currentValue.item we were able to have to access each item’s values of the object and now sum the products as expected. Is this array method called Array.reduce method not super powerful? it is, mapping through the array an iterates over each object at once and sum their values in just one line of code and one callback fn.

Why not using the Array.reduce method to remove duplicate values from an array? it will be exceptional!. Just watch and see.

const removeDup = arr => { return arr.reduce((wrapper, currentValue) => { if (wrapper.indexOf(currentValue) === -1) { wrapper.push(currentValue); } return wrapper; }, []);};
console.log(removeDup([“1”, “2”, “3”, “2”, “1”, “5”, “6”, “2”]));//[ ‘1’, ‘2’, ‘3’, ‘5’, ‘6’ ]

What do we have here? this is a function that takes a parameter which stands to be an array, we just removed the duplicate values and returned the unique values.

Very simple I believe. Ok, let us ride on. In the previous page, we mentioned that if the initial value is declared, the wrapper takes those values, that is what exactly happens here.

The initial value is an empty array, the wrapper becomes an empty array, in the function, we passed a condition which checks if the wrapper already has the current value in its array, if yes remove the duplicate value and push the unique keys to the wrapper.

Moreso if we look very well, we will see that after the condition we returned the wrapper and not the current value. the initial value declared determines what the wrapper is returned as. If the initial value is an array just as it is now it will print out as an array, likewise any prototype.

Note: this can be easily done with a method called Set method. this is an es6 array method that returns an object as its result. below is an example of it:

let result = new Set([“1”, “2”, “3”, “2”, “1”, “5”, “6”, “2”]);console.log(result);//Set(5) { ‘1’, ‘2’, ‘3’, ‘5’, ‘6’ } very simple I guess.

Lastly, we will look upon how to return an object as a result of the array been looped through. Let us imagine returning the array values as key and there index as there value…, very interesting!.

const makeKeyAndValueWithReduce = array => { return array.reduce((wrapper, currentValue, currentIndex) => { wrapper[currentValue] = currentIndex; return wrapper; }, {});};console.log(makeKeyAndValueWithReduce([“1”, “2”, “3”, “4”, “5”]));//{ ‘1’: 0, ‘2’: 1, ‘3’: 2, ‘4’: 3, ‘5’: 4 }

This is it, we are back on it again. Here we have our initial value to be an object which means that our result will be returning an object, currently,

the wrapper takes the initial value which is an object, being an object, we will now apply our object ways here, we made the values the keys to the object with the square notation of an object method and assigned there index to be there valued and finally returned wrapper.

I believe this write up is indeed helpful. more of its kind will always be talked on, as always very simple and understanding.

If you want to know more about an Object, Constructor, Es6 Classes and Prototypal inheritance, you are very much welcome to my medium page

In my next course, we will be understanding more about Array.reduceRight and Array.reduceLeft and we will likely flatter an array using Array.reduce method.

I am a very passionate Software Engineer {MERN STACK}, currently working with Descasio as a Junior Full Stack Engineer. I am open to new roles (Remote)