Array Iteration Methods: Filter and Reduce

Learn about the array iterations methods filter and reduce, and optimize the guess who game.

The reduce() method

The reduce() method is another method that iterates over each value of an array, calling a callback function each time. The main difference is that, instead of returning an array, it combines each result from the callback into a single value.

The callback to the reduce() method describes how to combine each value of the array to produce a cumulative running total and has four parameters:

  • An accumulator that stores the running total. The final value of this will be returned by the method.
  • The value of the current item in the array.
  • The index of the current item in the array.
  • A reference to the array itself.

Most of the time, only the first two parameters are used, and any that aren’t used don’t need to be referenced.

The following example adds up all the numbers in the array and returns the total:

Get hands-on with 1200+ tech skills courses.