reduce() Array Method in JavaScript

If reduce() was a person, it would be a census enumerator:

var pokemon = ["squirtle", "charmander", "bulbasaur"];

var pokeLength =
  pokemon.reduce(function(previous, current) {
  	return previous + current.length;
  }, 0);

// 27


reduce() goes over each array entry updating a reference to a key value that it ultimately returns:

array.reduce(function(previousValue, currentValue, currentIndex, array), {
	// do stuff here
	return newPreviousValue;
}, initialValue);


If you supply an initialValue, the key value starts off with that. Otherwise it starts with the array’s first element. In both cases, you can reference it using the previousValue argument in your callback function.

Remember that you must explicitly return something that will be the previousValue for the next entry in the array.


For a turn-by-turn explanation of the reduce method, head on over to Mozilla Developer Network


🔎 Searching...