When Should I use Array.reduce?

When Should I use Array.reduce?

When Should I use Array.reduce?

Javascript Arrays have many built-in array methods that can sort out some pretty complex logic for you. A simple example would be taking an array and doubling its values, or filtering for odd numbers in an array.

Here we have an array of numbers, and our task is to double each number our array. The easy choice would be to use Array.map. snippet.png

I should also point out that many of the built-in Array methods are performing some kind of reduction under the hood. Let's see how we would create our own Array.map using Array.reduce.

snippet (1).png

On every interaction, we push the new value into our array, but before doing so we double it.

Array.reduce is a great option for taking complicated data, sorting it to fit your requirement. I tend to reach for built-in Array methods as often as I can, I'll reach for reduce when there are multiple steps needed to configure data to work for my use case.

Here's an example when using a reduce would be a better choice. Given an array, with a random mix of numbers that we need double (again) but this time we also need to sort from largest to smallest, also let's remove any doubles. snippet (2).png

I know this is a contrived example, but once you understand how to use reducers, compartmentalizing your logic inside a reducer just works as expected. There are several ways to do this, but I can argue reduce is the most readable implementation.

When you can, reach for built-in array methods, when your logic is a bit more complex consider using a Array.reduce.