JavaScript Array reduce() Method

Photo by Markus Spiske on Unsplash

Array reduce method is a scary thing. It’s a method which works as alternate of for loop method .

The reduce() method reduces the array to a single value.

The reduce() method executes a provided function for each value of the array (from left-to-right).

The return value of the function is stored in an accumulator (result/total).

Reduce method with array :

reduce() method contains a callback function and an initial value. In the example of above, 0 is the initial value which is the value of sum. And num will go through the each element of nums array .the reduce method will go through the whole array and will return a single value. In this code it’ll return sum of the elements.

Reduce method with objects:

const friends = [{name: ‘Rashed’, money: 12},{name: ‘Kashed’, money: 25},{name: ‘Pashed’, money: 37},{name: ‘Nashed’, money: 29},{name: ‘Munia’, money: 100}];

const totalMoney = friends.reduce((sum, friend) => {

console.log(sum, friend);


}, 0);

Here, friends is an array object. We have applied reduce method on friends array object and the single value result will be in totalMoney variable. 0 is the initial value. It’s the value of sum. friend will go through the each element of friends. For calculating total sum of each friends money we have to write .

Front End Engineer | JavaScript Developer