For a lot of people, the first time when we know about .reduce
function in JavaScript is probably when we use it to sum up an array of numbers, like:
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
But there’s actually a lot more to that. For example, for who starts to use Redux, you may learn about the reducer function originates from .reduce
and even have had a look at the source code.
Back to the basics, essentially the reduce()
method executes a reducer function on each element of the array, resulting in single output value.
The reducer function takes four arguments:
- Accumulator (
acc
) - Current Value (
cur
) - Current Index (
idx
) - Source Array (
src
)
It optionally takes an initial value as well.
arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
So what are the use cases with advanced .reduce function?
Starting from the last example to count numbers, we can count an array of objects:
let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
(accumulator, currentValue) => accumulator + currentValue.x
, initialValue
)console.log(sum) // 6
We can use it to flatten arrays :
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( accumulator, currentValue ) => accumulator.concat(currentValue),
[]
)
//[0,1,2,3,4,5]
Structure an object:
For example, we want to group a list of objects by one of their common properties:
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
Now in order to group the people by age, we pass the objects into reducer.
function groupByAge(personsArray, property) {
return const personsArray.reduce( (acc, person)=> {
let key = person[property]
if (!acc[key]) {
acc[key] = [] //if this property does not exist on accumulator
} // object, then init as empty array acc[key].push(person) //if exist, then push the object in
return acc
}, {}) // note that accumulator is init as empty object
}
And then:
groupByAge(people, 'age')
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
Try it out yourself!