Open In App

How to use Array.prototype.reduce() method in JavaScript ?

The Array.prototype.reduce() method is used in an array to return a single value from an array after executing the user-supplied callback function on each element of the array. It transverses from the left-most-element to the right-most-element of the given array.

Array.prototype.reduce() can be called using two ways.



Syntax:

array.reduce( myFunction, initialValue )

Syntax:



reduce(function(returnValue, currentValue, currentIndex, array){ 
        ... }, initialValue)

Parameters:

Example 1: In this example, we will see the basic use of the Array.prototype.reduce() method using the callback function in Javascript.




const array = [10, 18, 30, 41, 60];
const myReducer = (returnValue,
    currentValue) => returnValue + currentValue;
 
// 10 + 18 + 30 + 41 + 60
console.log(array.reduce(myReducer));
// expected output: 159
 
// initialValue = 20
// 20 + 10 + 18 + 30 + 41 + 60
console.log(array.reduce(myReducer, 20));
    // expected output: 179

Output:

159
179

Example 2: In this example, we will see the use of the Array.prototype.reduce() method in Javascript.




const array1 = [1, 2, 3, 4, 5];
 
// Calculating sum of squares
const myReducer = (returnValue, currentValue) =>
    returnValue + currentValue * currentValue;
 
// 1 + 4 + 9 + 16 + 25
console.log(array1.reduce(myReducer));
// expected output: 55
 
// initialValue = 6
// 36 + 1 + 4 + 9 + 16 + 25
console.log(array1.reduce(myReducer, 36));
    // expected output: 91

Output:

55
91

Article Tags :