How to use Array reduce method in JavaScript

Javascript Nov 16, 2019

Say you have an array of numbers and want to sum them up into a single number to return from a function call. You could achieve this in several ways, but the most efficient will usually be to use the Array.prototype.reduce method on your array. Let's take a look at how to achieve that.

How to reduce an array

In order to reduce an array of elements into a single value, simply call its #reduce() method with a function as the first argument; the function you provide is called your reducer. Your reducer function accepts four arguments:

  1. Accumulator, which accumulates the final value as you iterate through the array. By default, on the first iteration through the array, when your reducer is called, thee accumulator will be the first element in the array. You can optionally provide your own starting value for the accumulator as the second argument when you call #reduce().
  2. Current value, which is the element in the array that your reducer operates on during each iteration. The current value will be different each time your reducer is called as you step through the array.
  3. Current index, which is the index of the array your reducer is operating on as it steps through the array. The current value is the element at the current index in the array.
  4. Source array, which is the array you called the #reduce() method on. This can be very handy when you don't otherwise have access to the array you're reducing.

You don't have to use all of these arguments. All you need, in most cases, are the first two arguments – the accumulator and the current value – in order to compute the final value of the accumulator.

Let's take a look at a simple example wherein we sum up an array of numbers by reducing it:

function computeSum(numbers) {
	return numbers.reduce((total, number) => {
		return total + number

computeSum([1, 2, 3]) // 6
computeSum([1]) // 1
computeSum([]) // 0

Your array can be of any type. Say you have an array of objects that all have a field you'd like to combine into a single field or string. You could easily achieve that by reducing the array:

const myFriends = [
  {name: 'Bob', age: 20},
  {name: 'Sally', age: 23},
  {name: 'Sasha', age: 24},

console.log(myFriends.reduce((str, friend, index, friends) => {
	if (index === 0) {
        return `${str} ${} (${friend.age})`
    } else if (index !== friends.length - 1) {
        return `${str}, ${} (${friend.age})`
    } else {
        return `${str}, and ${} (${friend.age}).`
}, 'My friends are'))

That prints "My friends are Bob (20), Sally (23), and Sasha (24)."

Go try it for yourself.

Bonus: Array.prototype.reduceRight Use reduceRight to reduce the array in reverse, from the right (last) to left (first) element.

Lincoln W Daniel

Full-stack software engineer, author of Java for Humans, designer.