English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript array reduce() method

 JavaScript Array Object

reduce()The method receives a function as an accumulator, starts reducing each value in the array (from left to right), and ultimately calculates a single value.

reduce()The method executes the callback function once for each array index.

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

Syntax:

array.reduce(callback, initialValue)
var nums = [10, 20, 30, 40, 50];
var sum = nums.reduce(getTotal);
function getTotal(x, y) {
return (x + y);
}
Test and see‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the reduce() method:

Method
reduce()is310.549

Parameter values

ParametersDescription
callback
A function that is run for each element in the array.
Function parameters:
  • accumulator(Required)- Function'sinitialValueor the value returned previously

  • element(Required)-The current element being processed in the array

  • index(Optional)-The index of the current element being processed in the array

  • array(Optional)- The array calledreduce()

initialValue(Optional) The value used as the first argument of the callback on the first call. If no initial value is provided, the first element of the array will be used.

Technical details

Return value:Reduce the number of generated values
JavaScript version:ECMAScript 5

More examples

This example removes duplicate items from the array:

var nums = [10, 20, 10, 20, 13, 5, 4, 5, 13, 4, 4, 4, 4]);
let result = nums.sort().reduce((accumulator, current) => {
const length = accumulator.length;
if (length === 0 || accumulator[length - 1)] !== current) {
accumulator.push(current);
}
return accumulator;
}, []);
function myFunc() {
   document.getElementById("result").innerHTML = result;
}
Test and see‹/›

Difference between reduce() and reduceRight():

var arr = ['1', '2', '3', '4', '5'];
function funcReduce() {
var val = arr.reduce(function(x, y) { return x + y;});
document.getElementById("result").innerHTML = val;
}
function funcReduceRight() {
var val = arr.reduceRight(function(x, y) { return x + y;});
document.getElementById("result").innerHTML = val;
}
Test and see‹/›

 JavaScript Array Object