published: 16 Jul 2022
2 min read
How to use the reduce() method in JavaScript
The reduce()
method reduces a JavaScript array into a single value. It executes the given reducer function for each array element except empty values, resulting in a single output value.
Here is what it looks like:
const callback = (accumulator, currentValue, index) => {
// TODO: do something here
}
const result = array.reduce(callback, initialValue)
initialValue
- The initial value you want to start with. It is used as the first argument to the first call of thecallback
. If skipped, the first element in the array will be used as the initial value.accumulator
- The value returned by the last invocation of thecallback
or theinitialValue
value for the first invocation.currentValue
- The current element being processed in the array.index
- The index of the current element being processed in the array. Starts from index 0 if aninitialValue
is provided. Otherwise, it starts from index 1.
Typically, the reduce()
method is used for calculating totals like sum, average, minimum, and maximum values in an array. It could also be used to sum values in an object array and flatten an array.
Sum all values of an array
Here is an example that calculates the sum of all elements in an array by using the reduce()
method:
const array = [1, 9, 7, 4, 3]
const sum = array.reduce((accumulator, current) => {
return accumulator + current
})
console.log('Sum of all numbers is ${sum}')
// Sum of all numbers is 24
In the above code, I used an arrow function for simplicity. A regular function can also be used as a callback.
You can also pass an initial value to add it to the total:
const array = [1, 9, 7, 4, 3]
const sum = array.reduce((accumulator, current) => {
return accumulator + current
}, 10)
console.log('Sum of all numbers is ${sum}')
// Sum of all numbers is 34
As you can see above, we passed 10
as an initial value, and it was added to the total.
Find maximum and minimum values
The reduce()
method can find the maximum and minimum values in an array.
Here is an example that finds the highest number in an array:
const array = [1, 9, 7, 4, 3]
const max = array.reduce((accumulator, current) => {
return accumulator > current ? accumulator : current
})
console.log('Maximum number is ${max}')
// Maximum number is 9
Similarly, to find the lowest number in an array, you can do the following:
const array = [1, 9, 7, 4, 3]
const min = array.reduce((accumulator, current) => {
return accumulator < current ? accumulator : current
})
console.log('Minimum number is ${min}')
// Minimum number is 1
Sum of values in an object array
The reduce()
function is not just limited to summing an array of numbers. You could also sum up the values contained in an array of objects. However, you must supply an initialValue
, so that each object goes through your callback function:
const array = [{ value: 5 }, { value: 1 }, { value: 2 }]
const sum = array.reduce((accumulator, current) => {
return accumulator + current.value
}, 0)
console.log('Sum of all object values is ${sum}')
// Sum of all object values is 8
Counting instances of values in an array
Another situation where you can use the reduce()
method is counting the number of occurrences of different values in an array.
Let us say you have got the following array of names:
const names = ['John', 'Alice', 'Maria', 'Mir', 'John']
Now, we want to know how many times each name appears in the array.
Since we want to reduce the array to an object, we must pass an empty object as the initialValue
:
const counts = names.reduce((accumulator, name) => {
// TODO: do something here
}, {})
In the first iteration, accumulator
will be {}
and name
will be John
. We can simply add name
to accumulator
and set the count to 1:
const counts = names.reduce((accumulator, name) => {
return (accumulator[name] = 1)
}, {})
In the next iterations, we will first check if the name
property already exists in accumulator
or not. If it does, we will only increment the count by 1:
const counts = names.reduce((accumulator, name) => {
if (name in accumulator) {
accumulator[name] = accumulator[name] + 1
} else {
accumulator[name] = 1
}
return accumulator
}, {})
That's it. Once the process is completed, the counts
variable should contain the following object:
{
'John': 2,
'Alice': 1,
'Maria': 1,
'Mir': 1
}
Flattening an array
The reduce()
method can also be used to flatten a multi-dimensional array:
const flowers = [['🍀'], ['🌷'], ['🌹'], ['🌻', '🌺']]
const flattened = flowers.reduce((accumulator, item) => {
return accumulator.concat(item)
}, [])
console.log(flattened)
// [ '🍀', '🌷', '🌹', '🌻', '🌺' ]
Are we missing something? Help us improve this article. Reach out to us.
How to use the reduce() method in JavaScript
The reduce()
method reduces a JavaScript array into a single value. It executes the given reducer function for each array element except empty values, resulting in a single output value.
Here is what it looks like:
const callback = (accumulator, currentValue, index) => {
// TODO: do something here
}
const result = array.reduce(callback, initialValue)
initialValue
- The initial value you want to start with. It is used as the first argument to the first call of thecallback
. If skipped, the first element in the array will be used as the initial value.accumulator
- The value returned by the last invocation of thecallback
or theinitialValue
value for the first invocation.currentValue
- The current element being processed in the array.index
- The index of the current element being processed in the array. Starts from index 0 if aninitialValue
is provided. Otherwise, it starts from index 1.
Typically, the reduce()
method is used for calculating totals like sum, average, minimum, and maximum values in an array. It could also be used to sum values in an object array and flatten an array.
Sum all values of an array
Here is an example that calculates the sum of all elements in an array by using the reduce()
method:
const array = [1, 9, 7, 4, 3]
const sum = array.reduce((accumulator, current) => {
return accumulator + current
})
console.log('Sum of all numbers is ${sum}')
// Sum of all numbers is 24
In the above code, I used an arrow function for simplicity. A regular function can also be used as a callback.
You can also pass an initial value to add it to the total:
const array = [1, 9, 7, 4, 3]
const sum = array.reduce((accumulator, current) => {
return accumulator + current
}, 10)
console.log('Sum of all numbers is ${sum}')
// Sum of all numbers is 34
As you can see above, we passed 10
as an initial value, and it was added to the total.
Find maximum and minimum values
The reduce()
method can find the maximum and minimum values in an array.
Here is an example that finds the highest number in an array:
const array = [1, 9, 7, 4, 3]
const max = array.reduce((accumulator, current) => {
return accumulator > current ? accumulator : current
})
console.log('Maximum number is ${max}')
// Maximum number is 9
Similarly, to find the lowest number in an array, you can do the following:
const array = [1, 9, 7, 4, 3]
const min = array.reduce((accumulator, current) => {
return accumulator < current ? accumulator : current
})
console.log('Minimum number is ${min}')
// Minimum number is 1
Sum of values in an object array
The reduce()
function is not just limited to summing an array of numbers. You could also sum up the values contained in an array of objects. However, you must supply an initialValue
, so that each object goes through your callback function:
const array = [{ value: 5 }, { value: 1 }, { value: 2 }]
const sum = array.reduce((accumulator, current) => {
return accumulator + current.value
}, 0)
console.log('Sum of all object values is ${sum}')
// Sum of all object values is 8
Counting instances of values in an array
Another situation where you can use the reduce()
method is counting the number of occurrences of different values in an array.
Let us say you have got the following array of names:
const names = ['John', 'Alice', 'Maria', 'Mir', 'John']
Now, we want to know how many times each name appears in the array.
Since we want to reduce the array to an object, we must pass an empty object as the initialValue
:
const counts = names.reduce((accumulator, name) => {
// TODO: do something here
}, {})
In the first iteration, accumulator
will be {}
and name
will be John
. We can simply add name
to accumulator
and set the count to 1:
const counts = names.reduce((accumulator, name) => {
return (accumulator[name] = 1)
}, {})
In the next iterations, we will first check if the name
property already exists in accumulator
or not. If it does, we will only increment the count by 1:
const counts = names.reduce((accumulator, name) => {
if (name in accumulator) {
accumulator[name] = accumulator[name] + 1
} else {
accumulator[name] = 1
}
return accumulator
}, {})
That's it. Once the process is completed, the counts
variable should contain the following object:
{
'John': 2,
'Alice': 1,
'Maria': 1,
'Mir': 1
}
Flattening an array
The reduce()
method can also be used to flatten a multi-dimensional array:
const flowers = [['🍀'], ['🌷'], ['🌹'], ['🌻', '🌺']]
const flattened = flowers.reduce((accumulator, item) => {
return accumulator.concat(item)
}, [])
console.log(flattened)
// [ '🍀', '🌷', '🌹', '🌻', '🌺' ]
Are you looking for other code tips?
JS Nooby
Javascript connoisseur