Understanding the `reduce()` array method in JavaScript

Understanding the `reduce()` array method in JavaScript

Array methods in JavaScript are a bunch of amazing higher-order functions that help us iterate over an array while performing certain transformations or computations on each of the array items.

It also helps us construct our code in a more elegant way and easy-to-read pattern. We can use array methods to get our code looking more beautiful and easy to read, some of those functions are quite easy to understand while the others are a bit harder to grasp.

In this article, I will be explaining the reduce() array method, how it is used, and when you should use it.

What is the Reduce array method in JavaScript

The reduce() array method is a higher-order function that takes an array and reduces it to one value. The value may be a number, string, object e.t.c.

The reduce() array method accepts two arguments:

  • The reducer function (Which you provide): This is a function that runs on every iteration of the array
  • Initial value: This is the initial value that you set for the iteration. Further down in this article I will explain how this is used.
array.reduce(  ()=>{},     0)

The reducer function which is provided also accepts 4 arguments:

  • Accumulator: This holds the current value that is returned after each iteration
  • current value: This is the current item in the array during the iteration
  • index: This is the index of the current value (Optional)
  • array: This is the original array on which the reduce method was called (Optional)

How you name the arguments are totally up to you , the only thing that matters is the order which the arguments appear

array.reduce( (accumulator, currentvalue, index, array)=>{ 
// return a value here}, 0   )

Example 1

The example below is using the reduce array method to reduce all the numbers in an array into one single number by adding them all up

const numbers = [1, 2, 3, 4, 5];

const sumOfNumbers = numbers.reduce((accumulator, currentValue)=>{
 return accumulator + currentValue
}, 0)

console.log(sumOfNumbers) // 15

// you can store your reducer function in a variable to
// make your code neater and more readable


const reducerFn = (accumulator, currentValue)=>{
 return accumulator + currentValue
}

const sumOfNumbers = numbers.reduce(reducerFn, 0)

console.log(sumOfNumbers) // 15

In the code snippet above, the initial value is 0 which becomes the accumulator value at the start f the iteration, then currentValue becomes 1 which is the first element on the array. The return value becomes the addition of the accumulator plus currentValue which is 0 + 1 = 1.

Remember the accumulator holds the value returned from the function, so after the first iteration the accumulator now holds 1 which is the returned value.

Note: The accumulator holds the initialValue provided during the first iteration but after that, the accumulator now holds the returned value.

For every iteration from the example above, the array is reduced by adding the numbers in the array.

Let look at another example of how the reduce() method is used.

Example 2

In this example, reduce() is used to transform an array into a single object that shows how many times each string in the array appears

const animalCounts = animals.reduce((obj, pet)=> {
    if(obj[pet]){
     obj[pet] ++
  }else{
      obj[pet]=1
    }
return obj
}, { })

console.log(animalCounts)
// Output
{
Dog: 3,
Sheep: 1,
Duck: 2,
Fish: 2

}

In the code snippet above, you can see how I set the initial value to an empty object, this is be passed into the accumulator argument in the reducer function as the first value during the first iteration, from the example above is named obj. The for every iteration, that function is executed.

It checks if obj has a property of the currentValue, if it does it increase the property value , else it creates and new property with the name of the currentValue and assign 1 to it, which will be increased on every iteration if found again in the iteration.

That all there is to the reduce() method, it is very helpful in solving problems related to array and you can solve such problems neatly and elegantly.

Conclusion

Thank you for sticking with me up till this point. If you enjoyed reading this article, please like and share it.

Have any questions? Drop them in the comment section below.

I would be posting more articles, so be sure to follow me to get notified when I post them.

If you have any questions concerning Go, Javascript, TailwindCSS, Open-source, or this article? You can reach me on Twitter. Till next time, see ya. Thank you.