Digging the Array.prototype.reduce() function in JavaScript

Digging the Array.prototype.reduce() function in JavaScript

"The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value." --- MDN Web docs.

This statement sounds so complex. I'll explain the reduce() function in much simpler words.

Let's take an array of grocery list which contains objects of individual item.

const foodItems = [
    {name: "Ice", price: 23},
    {name: "Fish", price: 67},
    {name: "Candy", price: 32},
    {name: "Oil", price: 35},
];

See the above array, now we have to find the sum total of the money spent i.e. sum of prices. But its a array of objects, how can we find the sum of that? Well follow along and you'll know.

So, first we'll use the map() function, another higher order function provided by JavaScript ( read about map() here).

const foodItems = [
    {name: "Ice", price: 23},
    {name: "Fish", price: 67},
    {name: "Candy", price: 32},
    {name: "Oil", price: 35},
];

let newArr = [];
foodItems.map((item) => {
    newArr.push(item.price); // Now we'll get a new array that contains the price list
})

const sumReducer = (prevValue, currentValue) => {return prevValue + currentValue}

const sum = newArr.reduce(sumReducer, 0);

// 157

What we are doing here is that first we are making an array out of the foodItems array by using the map() function. Then we created a sumReducer variable which is an arrow function. And this function takes two parameters, prevValue and currentValue, and returns their sum.

Next what we are doing is using the reducer function inside a variable. We passed the callback function and an initial value to it. And it will return 157, the sum of all prices.

But what is happening inside this reduce() function?

So, the reduce function takes two arguments, a callback, and the initial value (it can be a number or an object). The callback is the ‘reducer’, which takes 4 arguments, the accumulator, currentValue, index and array. As you can see in the above example our sumReducer only needs the accumulator and the currentValue as it is only a simple program. It then returns the value that it gets from the reducer function.

Now you might ask that what is the initialValue here is? So, initialValue is optional. But is you pass an initial value to the reduce() function then the prevValue will initialize at that initialValue. Lets take a look at our previous code.

const foodItems = [
    {name: "Ice", price: 23},
    {name: "Fish", price: 67},
    {name: "Candy", price: 32},
    {name: "Oil", price: 35},
];

let newArr = [];
foodItems.map((item) => {
    newArr.push(item.price); // Now we'll get a new array that contains the price list
})

const sumReducer = (prevValue, currentValue) => {return prevValue + currentValue}

const sum = newArr.reduce(sumReducer, 10);

// Not it will not return 157, instead it will now return 167

The about code now returns 167, why? Because we provided an initialValue of 10 to it, so now the prevValue will initialize at the given initialValue. But if we don not provide a initialValue then the prevValue will initialize at the first index of the given array.

Now what is I tell you that we can create our own custom reduce() function? yes we can!

Let's create our own reduce() function.

Let's take the same example of foodItems array.

const arr = [
    {name: "Ice", price: 23},
    {name: "Fish", price: 67},
    {name: "Candy", price: 32},
    {name: "Oil", price: 35},
]

let newArr = [];
arr.map((item) => {
    newArr.push(item.price);
    return newArr;
})

const reduce = (reducer, initialValue, array) => {
    let value = initialValue;

    for(let i = 0; i < array.length; i++) {
      let currentValue = array[i]
      value = reducer(value, currentValue)
    }

    return value;
}

const sum = reduce(sumReducer, 0, newArr);

// It will return 157

Yes it's that simple!

We've made our own reduce function. Wohoo!!

Stay hydrated. Keep learning.