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 :

const nums =[12, 25, 37, 29];

const total = nums.reduce((sum, num) => {

console.log(sum, num);

return sum+num;

}, 0);

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Realtime charts with JavaFX

Keycloak Integration With Gatsby/React

How to Add Custom JavaScript Actions Using Button Field with Meta Box

Create Custom Fields to Input Data with Meta Box

5 JavaScript Features That You Might Not Know About

A curious case of Javascript .apply() and Salesforce ActionFunction.

Node JS middlewares at a glance

How to install leaflet via npm

DSA: Sliding Window Pattern

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mowmita Ahmed

Mowmita Ahmed

Front End Engineer | JavaScript Developer

More from Medium

JavaScript Promises: Understanding Promise.all()

10 Important Array Methods In JavaScript Explained

JavaScript Testing with Jest

JS-07— JavaScript for Programmers, Chapter4to6, Summary, Part3