The JavaScript array reduce () method applies a function to two values (from left to right) of the array at the same time to reduce to a value.
Grammar
Array.reduce (callback[, InitialValue]);
The following are the details of the parameters:
- Callback: function executes each value in the array
- InitialValue: The first invocation of an object as the first parameter callback uses the
return value:
Returns the reduction of an array by a single value
Compatibility :
This approach is a JavaScript extension to the ECMA-262 standard; Therefore it may not exist in other implementations of the standard. To make it work, you need to add the top of the following scripting code:
if (! Array.prototype.reduce)
{
Array.prototype.reduce = function (Fun/*, initial*/)
{
var len = This.length;
if (typeof fun!= "function")
throw new TypeError ();
No value to return if no initial value and a 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) {
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)
RV = Fun.call (null, RV, this[i], I, this);
}
return RV;}
;
}
Example:
This will produce the following results: