javascript reduce

javascript reduce method

The javascript reduce method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

Directly copied from MDN

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring.

The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

Summary :-

The reduce method is an acculumator function that provides a simpler way to loop through any javascrpt array from left to right and perform incremental function on all the values.

Some examples to help better understand .reduce

1.Calculate the Sum

var calculateSum = function (a) {
	return a.reduce(function  (i,c) {
		return i+c

console.log(calculateSum([1,2,3,4])); // <= 10

2.Calculate the product of all the elements of the array :-

var calculateProduct = function  (a) {
	return a.reduce(function  (i,c) {
		return i*c;

console.log(calculateProduct([1,2,3,4])); <= 24

3. Calculate the sum of even elements

/* This can be achieved better by using filter Ex.5 */

  if(i%2 === 0){ 
   return a+b;
   return a;
}); //<= 4

4. Flatten an array

var flattenArray = function  (a) {
	return a.reduce(function  (i,c) {
		return i.concat(c);

var b = [[1,2,3],[2,3,4],[4,5,6]];

console.log(flattenArray(b)); //<= [ 1, 2, 3, 2, 3, 4, 4, 5, 6 ]

4. Flatten any array of any level recursively

Here we are passing the second argument as an empty array as that will be the initial value of the accumulator.

var b = [2,[1,2,[3,4]],[2,3,4],[4,5,6]];

var flattenRecursive = function  (arr) {
	return arr.reduce(function  (a,b) {
		if (b instanceof Array) {
			return a.concat(flattenRecursive(b));
			return a.concat(b);

console.log(flattenRecursive(b)); //<= [ 2, 1, 2, 3, 4, 2, 3, 4, 4, 5, 6 ]

5. Using with filter to solve Ex.2

Using filter with reduce makes looping through any array and performing any function much easy.

var filterEvenSum = function  (arr) {
	return arr.filter(function  (a,i) {
		return !(i%2);
	}).reduce(function  (a,b) {
		return a+b;

console.log(filterEvenSum([1,2,3,4])); //<= 4

Main Source :

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>