JavaScript Array reduce() Definition
The reduce () method reduces the array to a single value. executes a function provided from left to right for each value of the array. reduce() does not execute the function for array elements without values.
Syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
total(required): The initialValue, or the previously returned value of the function.
currentValue(required): The value of the current element
currentIndex(optional): The array index of the current element
arr(optional): The array object the current element belongs to
JavaScript Array reduce() Examples
Example 1
let names = ["john", "alex", "oliver"];
let process = names.reduce(function (x, y) {
return x + y.length;
},0)
console.log(process)
output:
14
Example 2
var numbers = [15, 10, 5, 2];
function getSum(total, num) {
return total + Math.round(num);
}
console.log(numbers.reduce(getSum,0))
output:
32
Example 3
var users = [{
name: 'Anna',
password: ['anna123']
}, {
name: 'Bob',
password: ['bob123']
}, {
name: 'Alice',
password: ['alice123']
}];
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var userProcess = users.reduce(function (x, y) {
return [...x, ...y.password];
}, ['password']);
console.log(userProcess)
output:
[“password”, “anna123”, “bob123”, “alice123”]
Polyfill
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, 'reduce', {
value: function(callback /*, initialValue*/) {
if (this === null) {
throw new TypeError( 'Array.prototype.reduce ' +
'called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback +
' is not a function');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// Steps 3, 4, 5, 6, 7
var k = 0;
var value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in o)) {
k++;
}
// 3. If len is 0 and initialValue is not present,
// throw a TypeError exception.
if (k >= len) {
throw new TypeError( 'Reduce of empty array ' +
'with no initial value' );
}
value = o[k++];
}
// 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// « accumulator, kValue, k, O »).
if (k in o) {
value = callback(value, o[k], k, o);
}
// d. Increase k by 1.
k++;
}
// 9. Return accumulator.
return value;
}
});
}
Browser Support
| Chrome | yes |
| Edge | yes |
| Firefox | 3 |
| Internet Explorer | 9 |
| Opera | 10.5 |
| Safari | 4 |
| Android webview | yes |
| Chrome for Android | yes |
| Edge mobile | yes |
| Firefox for Android | 4 |
| Opera Android | yes |