How to use Array reduce method in JavaScript

In order to reduce an array of elements into a single value, perhaps a sum or aggregate, simply call its reduce method.

Lincoln W Daniel
Nov 17, 2019 · 3 min read

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().

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.

This article was originally published on


Explaining code 1 line at a time.

Lincoln W Daniel

Written by

My passion is in developing software to enable people to accomplish their goals more efficiently. Author Creator of



Explaining code 1 line at a time.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade