Code Synopsis logo

How do I use JavaScript Array.reduce()?

Like many array methods, Array.reduce() iteratively applies a function to the array items, but what makes reduce special is that it feeds the output of the first iteration into the next. The passed value will accumulate changes in each cycle. This results in a single value of any data type. You are not manipulating the original array but computing a value.

With the Array.reduce() method you can do things like:

  • Compute the sum of all numbers
  • Count items that pass a test
  • Reorganize array items in a new array or object
  • Create a new string based on test results

Let’s get the sum of numbers:

const numbers = [25, 1, 14, 7]; const sum = numbers.reduce((count, num) => (count += num)); console.log(sum);

The first argument is often called the accumulator because it accumulates changes as your function progresses through its iterations. It is the seed value for the first cycle.

By default, the accumulator value is the first value in the array. In the example above, the accumulator count has a value of 25.

How many Bobs are in the array:

const names = ["Pedro", "Bob", "Tyrone", "Sandy", "Bob", "June"]; let countedNames = names.reduce((nameCount, name) => { if (name === "Bob") {nameCount++;} return nameCount; }, 0); console.log(countedNames); // 2

In the above example, we have assigned an initial value to the accumulator of 0. If we didn’t do this, the accumulator nameCount would have had a default value of Pedro. The accumulator’s initial value is set at the end of the function call.

The Array.reduce() arguments

The reduce method requires a function with at least two but can accept up to four arguments.

The first argument is the accumulator, and the initial value is set at the end of the function call if you want to replace the default value.

}, 0);

The initial value can be any data type. It could be an array or object that is already populated with data, which makes reduce versatile.

The second argument, gives you access to each element in the original array as reduce iterates through it. Our example used the word name because our original array is an array of names. We used it to check if any names matched our search term ("Bob").

if (name === "Bob") { ...

The third argument is optional, and it gives you access to the index of the element in each iteration.

The fourth argument is also optional, and it gives you access to the original array.

Related posts:

Helpful references:

Have feedback on this topic?