Open In App

JavaScript Array reduce() Method

The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. 

Syntax: 

array.reduce( function(total, currentValue, currentIndex, arr), 
initialValue )

Parameters:

This method accepts five parameters as mentioned above and described below:



Return value:

The JavaScript array reduce method returns a single value/element after traversing the complete array.

Below are examples of the Array reduce() method.



Example 1: In this example, we will write a reduce function to simply print the difference of the elements of the array.




// Input array
let arr = [175, 50, 25];
 
// Callback function for reduce method
function subofArray(total, num) {
    return total - num;
}
 
//Fucntion to execute reduce method
function myGeeks(item) {
    // Display output
    console.log(arr.reduce(subofArray));
}
myGeeks()

Output
100

Example 2: This example uses reduce() method to return the sum of all array elements. 




// Input array
let arr = [10, 20, 30, 40, 50, 60];
// Callback function for reduce method
function sumofArray(sum, num) {
    return sum + num;
}
//Fucntion to execute reduce method
function myGeeks(item) {
    // Display output
    console.log(arr.reduce(sumofArray));
}
myGeeks();

Output
210

 Example 3: This example uses reduce() method to return the round sum of all array elements. 




// Input array
let arr = [1.5, 20.3, 11.1, 40.7];
 
// Callback function for reduce method
function sumofArray(sum, num) {
    return sum + Math.round(num);
}
 
//Fucntion to execute reduce method
function myGeeks(item) {
    // Display output
    console.log(arr.reduce(sumofArray, 0));
}
myGeeks();

Output
74

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers: The browsers supported by JavaScript Array reduce() method are listed below:

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


Article Tags :