#100DaysOfCode Day 10: Reduce

Shawn McMahon
2 min readJul 22, 2021

Reduce

Today is dedicated to my little friend Reduce. Reduce and I have a love-hate relationship. At first, I despised being reduced. It confused me. It made absolutely no sense. But then over time, I began to see the magic of Reduce and how powerful it is. Now I have trouble not using reduce since it’s so versatile. There is usually a better, more direct method that can be used in most cases.

Coffee poured from a pot into a beaker

Reduce is an array iterator method. Reduce will take in an array as an input and output what is known as an ‘accumulator’ (acc). It’s magic lies within this accumulator. This accumulator can be any data type, not just an array. That means we can output an integer, string, boolean, array, or object! Super useful.

Code snippet of reduce example

In the example below, we have an arrayOfNumbers. We define a new variable assigned to the reduce method. The reduce uses the arrayOfNumbers and takes in 2 parameters; acc and currentNumber. We know what the ‘acc’ is. So what is the 2nd parameter? This parameter is a semantic representation of the current index in the array that is being evaluated. Since we know we are working on an array of numbers, I am going to call this variable currentNumber.

Code snippet of reduce example

We then move onto the logic inside the reduce. Every single number in the arrayOfNumbers will be evaluated through this logic. Our currentNumber will only be pushed into the accumulator if it’s remainder is strictly equal to 1, making it an odd number. Once the reduce reaches the end of the arrayOfNumbers, it will stop and return that output to the AllOddNumbers variable.

We now have all odd numbers from the original array ~ magic!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shawn McMahon
Shawn McMahon

Written by Shawn McMahon

Software Engineer, Snowboarder, Music Enthusiast

No responses yet