We’ve all seen it — the quintessential reduce example taken from ancient tablets passed down from our people, just beneath console.log('hello, world! .

In case you’re not sure what I’m talking about, I’ll show you:

From MDN —

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

So you might be thinking to yourself, this will be so useful for when I have to find the sum of an array of numbers in my next production-grade app.

But the reduce function ends up being so handy. I think it’s one of those things that you don’t need until you need it.

As I worked through Whiz Tutor’s new mobile app, I found a great use for reduce . Tutors are able to set their availability by choosing time blocks that they are free to tutor. It looks like this:

What a tutor sees

On the other end, a student is able to choose individual time blocks by the hour:

What a student sees

So where does reduce come in? Let’s take a look at how a tutor’s availability is getting sent back to us when we send a GET request to obtain a specific user:

That is to say, to access the entire all_times array, we would call something like tutor.all_times . The problem with this data is that it needs to be sorted in some way. How would we do that? Sure, we could do something like sort by day. But then we would still end up with an array of objects. What if I only want to grab a tutor’s availability for Mondays?

Remember that reduce applies a function against an accumulator and reduces it to a single value. In theory, we could reduce this array into a single object where each key represents a single day. The values for each day could be an array of available time slots. In practice, that might look something like this:

In line 2, we get a copy of our array by using slice . Then, we sort the array to make sure that individual time blocks themselves are in sequential order.

Now for the interesting stuff. Remember that we’re turning this array into an object. Our reduce function iterates over every object in the array and looks at the day_string property. If the day_string property does not exist as a key in the reduced object, it will set it as a new key with the value of the entire object. Whew, that was a mouthful, but stick with me here.

If the value of day_string does exist, we can then spread the current objects in the array that it holds and add in the new object as well.

The output will look like this: