Skip to main content

Command Palette

Search for a command to run...

Array.reduce in the wild

Published
2 min read
Array.reduce in the wild
A

Lately, I've been spending a lot of time learning and implementing micro transitions and animations on web components using state machines to manage component state and have recently had an article featured on Hashnode on XState.

I lead a react learning group, we start at the fundamentals, and work our way up through advanced hooks.

In a previous life, I served as a company founder within the NYC food scene, making me accustomed to fast-paced environments that require sharp attention to detail. I understand the importance of a team and communication within that team.

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.

snippet.png

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.

snippet (2).png

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.

snippet (3).png

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.

More from this blog

Ariel Rodriguez's Dev Blog

12 posts

Lately I've been writing tutorials about web development topic's that interest me, may have stumped me, or something new that I'm just learning.