The JavaScript Array reduce method iteratively reduces an array to a single value using a callback function.
array.reduce(callback [, initialValue])For browsers that don't support the Array reduce method, here's an alternative implementation:
/**
* Copyright (c) Mozilla Foundation http://www.mozilla.org/
* This code is available under the terms of the MIT License
*/
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(fun /*, initial*/) {
var len = this.length >>> 0;
if (typeof fun != "function") {
throw new TypeError();
}
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
}
else {
do {
if (i in this) {
var rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len) {
throw new TypeError();
}
}
while (true);
}
for (; i < len; i++) {
if (i in this) {
rv = fun.call(null, rv, this[i], i, this);
}
}
return rv;
};
}Array ObjectIf you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.
Copyright © 2010-2011 Dive Into JavaScript