Real-world uses for Array.reduce
Many of the examples we've gone through have been contrived and unrealistic of the kind of data we manage daily. In this example we'll go through some more complex data, and grabbing only what we need using Array.reduce.
Picture making an API get request to an Emoji website, and we request transport emojis. Our request returns an array of objects, with a key/value of transport and available emojis. Our goal here is to transform this array, into a single array of all transports, and remove any duplicates.
We could write a helper function that first, maps through our array, then filters any doubles. But that's not why you're here. Let's use Array.reduce to create our new array.
Let's step through our code here so we can wrap our head around how this is working.
- We create a variable called
mappedAndFiltered
. - The first iteration gets our car's transport array, and we use Array.concat to add our cars into our empty array.
- This continues for every item in our emoji / transport array.
- Before we return the array, we use the new Set object. Set will only store unique value, so any doubles won't be added to our array.
- We use the spread operator to return an array. Set defaults to an object.
Let's add some additional complexities to our data. Maybe, the database sends nested array inside of the transport array. Again, this example is contrived, but you can see how powerful Array.reduce can be if you understand how to use it.
We can use the same method here, but we add the flat method and pass in Infinity. This will ensure deeply nested arrays are flattened. We are leveraging several Array methods and using them inside of our reducer.
I encourage you the next time you're building a helper function that is reducing an array, try using Array.reduce as an exercise. You'll start to notice it's a lot more useful than you realize.