JS reduce


JS Array.reduce() method combines the array elements to a single value according to specific function.

var arr = new Array(1,2.3,2,3,4,8,12,43,-4,-1);
var func = function (accu, elem) { return Math.max(accu,elem); }
var ret = arr.reduce(func);
alert(ret);  //43

reduce(func, val) method takes 2 arguments, the 1st is the function, the 2nd (optional) is the initial value of the calculation. When there is no initial value provided, it will be the first element of the array.

The specified function can take 4 arguments in the order of accumulator, value, index (optional) and the array (optional).

ret = arr.reduce(func, 45);
alert(ret);  //45

var func2 = function (accu, elem) { return accu * elem; }
ret = arr.reduce(func2);
alert(ret); //911462.4
ret = arr.reduce(func2, 2);
alert(ret); //1822924,8

Let's get the unique elements of an array:

var arr = new Array(4,32,29,4,2,3,4,32);
var ret = arr.reduce(
	function(accu, elem)
	{
		if (!accu.includes(elem)) 
		{
			accu.push(elem);
		};
		return accu;
	},[]);
alert(ret);  //4,32,29,2,3

reduceRight() is similar to reduce(). Except that it calculates from the right to left, or the last element to the 1st element.