English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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).
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‹/›
The numbers in the table specify the first browser version that fully supports the reduce() method:
Method | |||||
reduce() | is | 3 | 10.5 | 4 | 9 |
Parameters | Description |
---|---|
callback | A function that is run for each element in the array. Function parameters:
|
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. |
Return value: | Reduce the number of generated values |
---|---|
JavaScript version: | ECMAScript 5 |
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‹/›