The Simplicity of Reduce

Jake Young
2 min readMar 16, 2021

When I first began learning higher order functions in JavaScript, I managed to grasp concepts like filter and map with ease. Filtering is a common concept that exists outside of coding and mapping was very similar to how we edited our datatypes like arrays with for loops. However, understanding reduce took additional time and effort. There was something about having an optional seed parameter that would cause my brain to panic, especially in cases where the function wasn’t reducing to a number. That being said, conquering reduce can actually make your life as a coder much easier in the long run. Take this simple example as proof:

In this example, we have an animals array filled with animal objects and we want to obtain only the lions, specifically just their names.

const animals = [

{ name: ‘James’, age: 2, species: ‘giraffe’ },

{ name: ‘Nina’, age: 5, species: ‘zebra’ },

{ name: ‘Veronica’, age: 3, species: ‘elephant’ },

{ name: ‘Oscar’, age: 6, species: ‘elephant’ },

{ name: ‘Omar’, age: 2, species: ‘elephant’ },

{ name: ‘Lucy’, age: 2, species: ‘lion’ },

{ name: ‘Lucky’, age: 1, species: ‘lion’ },

];

There are at least a couple of ways to go about this-

  1. You could use filter to strictly obtain the lion objects then map to obtain the name’s within those objects like so:

const lionNames = animals.filter(function(animalObj){

return animalObj.species === ‘lion’;

}).map(function(lions){

return lions.name;

})

console.log(lionNames)

// => [‘Lucy’, ‘Lucky’]

2. Perhaps a more efficient way would be to use reduce. Why use two functions to do the job of one? In this example, we set up a seed array called lionArr, verify the lion objects via an if-conditional, push their names in the seed parameter, then return this array of lion names. Super Efficient!

const allLions = animals.reduce(function(lionArr, animalObj){

if (animalObj.species === ‘lion’){

lionArr.push(animalObj.name);

}

return lionArr;

}, [])

console.log(allLions)

//=>[‘Lucy’, ‘Lucky’]

Reduce can take the powers of filtering and mapping and combine them into one function! In our example above, if we just filtered, we would have received the lion objects and would not have been able to strictly return their names. Furthermore, in our reduce example we could have also easily returned the age of the lions instead of the name by switching the dot notation on animalObj to animalObj.age.

This is just a small example of how learning to apply reduce in your coding can shorten your function usage and make your life a little easier!

--

--