The Array Object in Javascript supports several methods that you can use to manipulate the array elements. These include the array.map()
, array.sort()
, array.filter()
, array.reduce()
etc. The latter – array.reduce()
method – is regarded as one of the most tricky array methods and can be quite hard to understand at first glance. However, it’s a powerful method and is a key component of functional programming in Javascript.
The array.reduce()
method is a built-in Javascript method that reduces all the elements in an array to a single value while preserving the original array. That single value can be of any type – string, number, object, etc.
This post will provide a comprehensive guide on the Array.reduce()
method in JavaScript. We will look at its syntax, properties, and several examples in code to help you understand the concept better. We will also give you an insight into the Array.reduceRight()
method, which works similarly to the Array.reduce()
method.
Table of Contents
Introduction to the Array.reduce()
Method in Javascript
Let’s look at the array of numbers below.
const numbers = [1,2,3,4,5]
We can use various methods to get the sum of all the elements in the array. Let’s start with the forEach()
method in Javascript.
const numbers = [1,2,3,4,5]
let sum = 0
for(let item of numbers){
sum = sum + item
}
console.log(sum)
//Result: 15
Here, we are using a pretty simple algorithm. First, we declare a variable called ‘sum’ and initialized it to zero (0). Using the forEach()
method, we loop over the array and get each array item one by one as we add it to ‘sum’ after every iteration. In simple terms, we reduced our array to a single value. In this case, a number
Even though this method helped us achieve what we wanted, there is a more cleaner and elegant method that we can use – the Array.reduce()
method.
const numbers = [1,2,3,4,5]
const sum = numbers.reduce(function(accumulator, initialValue){
return accumulator + initialValue
},0)
console.log(sum)
//Result: 15
That looks pretty simple. Right? Well, let’s look at the Array.reduce()
method in detail.
The Array.reduce()
Method Syntax
The array.reduce()
method takes two arguments – a callback function and an initial value.
array.reduce(callbackFunction[, initialValue]);
Let’s have an in-depth look at these two arguments.
- The callback function argument
- The initialValue argument
The Callback Function in Array.reduce()
Method
The Array.reduce()
method invokes the callback function on every item in the array. That callback function also takes four arguments – accumulator/total, currentValue, currentIndex and array. Therefore, another way we could write the Array.reduce()
syntax is shown below.
array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)
accumulator
: This is a required argument and is also known as ‘total.’ It holds the initialValue when the callback function is first invoked. In the other successive calls, the accumulator always holds the last value returned by the callback function.
If an initialValue is not provided, the accumulator uses the first array element (index zero) as the initialValue.currentValue
: This is also a required argument that holds the currently executed element of the array. When the callback function is first invoked, the currentValue holds the first element of the array (index zero).
However, if an initialValue was not provided, it holds the array’s second element (index one).currentIndex
: This is an optional argument and can be omitted. It stores the index of the currentValue in the array. When the callback function is first invoked, it is always set to index zero (first array element) if an initialValue was provided. Otherwise, it will be set to index one (second array element)array
: This is also an optional argument and can be omitted. It holds the complete array that the reduce() method works on.
You can learn more about callback functions in our post “The Ultimate Guide to Callback Functions in JavaScript.”
The Initial Value Argument
This is an “optional” argument that holds the first value passed to the callback function. If this value is not provided, the callback function will use the first element (index zero) of the array as the initialValue.
Tip: Here, we are using the word optional in quotes because there are certain Array.reduce()
programs that would not work without an initialValue.
Understanding the Array.reduce()
Logic
The table below shows you the logic that is used when you pass/ not pass an initialValue.
initialValue | Accumulator | currentValue | currentIndex |
Passed | initialValue | The first element of the array. | The first element of the array. |
Not passed | The first element of the array | The second element of the array | The first element of the array. |
Now that you have a good understanding of the Array.reduce()
method, let’s have an in-depth look at the code above where we were getting the sum of all array elements.
Tip: We have tweaked the code a little so that we can see what is happening step-by-step.
const numbers = [2,3,4]
const log = console.log
const sum = numbers.reduce(function(accumulator, currentValue){
log(`accumulator_Value = ${accumulator}`)
log(`currentValue = ${currentValue}`)
return accumulator + currentValue
},0)
console.log(`Total Sum = ${sum}`)
Output:
//First Call
accumulator_Value = 0 //same as initialValue
currentValue = 2
//Second Call
accumulator_Value = 2
currentValue = 3
//Third Call
accumulator_Value = 5
currentValue = 4
Total Sum = 9
Explanation:
When the callback function was first invoked, the accumulator had a value of zero (0) which is the initialValue that we passed. The currentValue on the other hand had a value of ‘2’ which is the first element of the array. The callback function did a sum of the accumulator value and currentValue (0 + 2) and this result was stored in the accumulator.
In the second iteration, the accumulator had a value of ‘2’, and the currentValue now held the second item of the array ‘3.’ Again, the function did a sum of the accumulator value and the currentValue (2 + 3), and this value was stored in the accumulator. This process goes on and on until the reduce method has looped through all the elements in the array.
The ES5 version of the Array.reduce()
Method.
As you might know, Javascript conforms to the ECMAScript specifications. As of writing this post, the most popular editions in the developer’s community are Javascript ES5 (2009) and Javascript ES6 (2015).
All the code we have written up to this point conforms to the ES5 edition. In ES5, we need to have parentheses and a return statement when writing functions as shown in the code below.
const numbers = [item,item,item,item,item]
const sum = numbers.reduce(function(accumulator, initialValue){
return accumulator + initialValue
},0)
The ES6 version of the Array.reduce()
Method
The ES6 edition introduces the use of Arrow functions in Javascript. Let’s convert the code above to use arrow functions.
const numbers = [item,item,item,item,item]
const sum = numbers.reduce((accumulator, item)=>(accumulator + item),0)
Alternatively, you can include the ‘return’ statement by adding parentheses as shown below.
const sum = numbers.reduce((accumulator, item)=>{
return accumulator + item
},0)
Array.reduce() Method Examples
Up to this point, we have had a good understanding of the Array.reduce()
method syntax and its logic. Let’s now have a look at more examples to better understand the concept.
Tip: Most of the examples that we will look at in this post will make use of the Arrow function syntax.
Example 1: Get the Sum of Elements in an Array
Let’s take an array of student marks as shown below.
const marks = [56,58,63,72,80]
To get the total marks using the Array.reduce()
method, we will write the code as shown below.
const sum = marks.reduce((accumulator, arrayItems)=>(accumulator + arrayItems),0)
console.log(sum)
That was quite easy, right? We are iterating through the elements in the array and adding them to the accumulator. Let’s look at more complex examples where we have an array of objects.
Example 2: Summing Values in an Object
Let’s take a look at the array of objects below.
let person =[
{name:"Karen", age:24, hobby:"dancing"},
{name:"John Doe", age:23, hobby:"riding"},
{name:"Nikita", age:15, hobby:"drawing"},
{name:"Jane", age:24, hobby:"swimming"},
{name:"Benn", age:23, hobby:"travelling"},
]
To get the ‘sum’ of all ages in the array, we will write our code as shown below.
const sum = person.reduce((accumulator, arrayItem) => {
return accumulator + arrayItem.age
},0)
console.log(sum)//Result: 109
Here we are using a pretty straightforward logic. We first initialize the accumulator to zero (0) and then iterate through the ‘person array’ to fetch an element starting with index zero.
We then retrieve the age value from this element (arrayItem.age
) and add it to the accumulator. This loop continues until we have fetched every item from the array.
Example 3: Grouping Items with the Same Values
The Array.reduce()
method also comes quite in handy when you want to group items with the same values. For example, let’s group the people who have the same age in the ‘person array.’ We should end up with a list like;
{15: [person_1,person_2]}
We will write our code as follows.
const groupedByAge = person.reduce((accumulator, arrayItem)=>{
let age = arrayItem.age
if(accumulator[age] == null) accumulator[age] = []
accumulator[age].push(arrayItem.name)
return accumulator
},{})
console.log(groupedByAge)
Output:
{15:["Nikitah"],
23:["John Doe", "Benn"],
24:["Karen", "Jane"]}
In this example, you will notice that we are reducing our array into an object. We start by initializing our initialValue as an empty object ({}
). Next, we declare a variable ‘age’ that stores the ‘age value’ from the fetched from the array element (let age = arrayItem.age
).
We then write an ‘if statement’ that checks whether the accumulator (which holds our initialValue at the first iteration) has an item equal to that age. If it doesn’t have that item, we assign the item an empty array where it will add people of that age.
Example 4: Counting the Instances of an Item in an Array
This example is slightly similar to Example 3. Here, we want to calculate the instance of an item in an array.
Let’s use the array of laptop brands below.
const laptops = ["Dell","HP","Dell","Toshiba","Toshiba","Apple"]
We will write our code as shown below.
const instances = laptops.reduce((accumulator, currentValue)=>{
if (accumulator[currentValue] == null) { accumulator[currentValue] = 1 }
else {
accumulator[currentValue] +=1
}
return(accumulator)
},{})
console.log(instances)
//Result:{Dell:2,HP:1,Toshiba:2,Apple:1}
Here, we first set our initialValue to an empty object. Next, we write an ‘if statement’ that checks whether the currentValue is already in the accumulator. If the currentValue is not in the accumulator, we add this value and set it to 1 which is the current laptop brand. However, if the currentValue is already in the accumulator, we add 1 to its existing value.
See the logic below:
//First Iteration
accumulatorValue ={} //The accumulator is an empty object same as initialValue
currentValue = "Dell" //adds value to accumulator
accumulatorValue {Dell:1}
//Second IterationaccumulatorValue ={Dell:1}
currentValue = "HP" //adds value to accumulator
accumulatorValue {Dell:1, HP:1}
//Third IterationaccumulatorValue ={Dell:1, HP:1}
currentValue = "Dell" //adds value to accumulator
accumulatorValue {Dell:2, HP:1}
//Fourth IterationaccumulatorValue ={Dell:1, HP:1}
currentValue = "Toshiba"
accumulatorValue {Dell:2, HP:1, Toshiba:1}
//This loop continues until we have iterated through all elements in the array.
Example 5: Reducing an Array of Arrays
What if you have an array inside an array and you wish to reduce the entire array to a single value?
Let’s have a look at the example below.
Const pointsArray = [[2,3],[4,5],9,[7,8]]
To reduce this array to a single array, we will use the Array.reduce()
method together with the concat()
method as shown below.
const reducedArray= pointsArray.reduce((accumulator, currentValue)=>{
return accumulator.concat(currentValue)
},[])
console.log(reducedArray)
//Result
[2, 3, 4, 5, 9, 7, 8]
Since we want to reduce our ‘pointsArray’ to an array, we will set the initial value to an empty array ([ ]
). We then use the concat()
method which concatenates/ joins the elements (currentValue) we fetch from the array during each iteration.
Our short program uses the logic below.
//First Iteration
accumulatorValue =[] //The accumulator is an empty array same as the initialValue
currentValue = [2,3] //add to accumulator
accumulatorValue [2,3]
//Second Iteration
accumulatorValue =[2,3]
currentValue = [4,5] //add to accumulator
accumulatorValue [2,3,4,5]
//Third Iteration
accumulatorValue =[2,3]
currentValue = [9] //add to accumulator
accumulatorValue [2,3,4,5,9]
//This loop continues until we have iterated through all elements in the array.
Example 6: Remove Duplicate Items
Another scenario where you can apply the Array.reduce()
method is when you want to remove duplicate items from an array. Take a look at the array of numbers below.
const repeatedNums=[1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9]
To remove all duplicate numbers in this array, we can use the Array.reduce()
method shown below.
const reducedArray = repeatedNums.reduce((acc, curr)=>{
if(acc.includes(curr) === true){}
else{
acc.push(curr)
}
return acc
},[])console.log(reducedArray)
//Result: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Here, we first set our initialValue to an empty array. We then loop through the array and fetch an item. Next, we use a conditional statement to check whether this item is already in the accumulator. If it’s already in the accumulator, we do nothing, however, if it’s not, we add it to the accumulator.
The Array.reduceRight()
Method
The Array.reduceRight()
works just like the Array.reduce()
method with only one difference.
- The
Array.reduce()
method loops through an Array starting from the first (index zero) element to the last. - The
Array.reduceRight()
method loops through the array starting from the last element to the first.
Let’s understand this better in code.
//Array.reduce() Method
const arr = [1,2,3,4,5]
const loopItems = arr.reduce((acc, curr)=>{
console.log(curr)
return acc
},0)//Result: 1,2,3,4,5
From the output above, you can see that the Array.reduce()
method looped through the array starting with the first time to the last.
//Array.reduceRight() Method
const arr = [1,2,3,4,5]
const loopItems = arr.reduceRight((acc, curr)=>{
console.log(curr)
return acc
},0)//Result: 5,4,3,2,1
From the output above, you can see the Array.reduceRight()
method looped through the array starting with the last item to the first.
Common Mistakes to Avoid
- Always remember to pass the initialValue of the
Array.reduce()
method, unless you are 100% sure you wouldn’t need it in your program. - Don’t forget the ‘return’ statement especially if you have parentheses in your callback function. If you don’t, you will keep getting the error “accumulator is undefined.” Also, double-check your code to ensure you are returning the right value.
Conclusion
This post has given you a comprehensive guide on the Array.reduce()
method and how to use it to reduce an array to a single value. We have also looked at the Array.reduceRight()
method which works similarly to the Array.reduce()
method.
Was this article helpful?
Share it with other developers who want an in-depth explanation of the Array.reduce()
method. You can also share your thoughts by replying on Twitter of Become A Better Programmer or to my personal account.