RadDevon

How to Use Javascript's Array reduce Method

Javascript’s array reduce method iterates through an array and returns a single value. That may not help you understand how you can use it, but that’s because it can be used in so many different ways. The simplest use case for reduce is to add all the values in an array together.

[1, 2, 3, 4, 5].reduce((accumulator, num) => accumulator + num); // returns 15

Let’s take a look at a more complex example. We’re going to take a string of query parameters and parse them to an object. If we have a query string of name=Devon&age=35, we want to get back this object:

{ name: 'Devon', age: '35' }

reduce takes two arguments: a function to run on each item in the array and an initial value. You might notice that, in the previous example of the addition accumulator, I didn’t pass the initial value. If you leave it out, reduce will use the first value in the array as the initial value. In our query parameter case, that won’t work since we need to build an object while each of the values in our array is a string.

When reduce calls the function you pass in, it passes it three arguments: the value of the accumulator, the array item, and the array index. In our case, we only care about the first two.

const queryParams = queryParamsString .split('&') .reduce((accumulator, singleQueryParam) => { const [key, value] = singleQueryParam.split('='); accumulator[key] = decodeURIComponent(value); }, {});

Here’s the breakdown. We have a constant queryParams that we’re assigning the value returned by the rest of the code here. We split queryParamsString on the ampersand which gives us an array of strings, each containing the string for a single query parameter. Here’s what that array would look like given the example query string earlier in the post: ['name=Devon', 'age=35']

Then, we reduce that array of query parameter strings starting with an empty object as the accumulator. (You’ll find that empty object passed in just before the closing parenthesis of the reduce call.)

To do that reduction, we first split the current parameter string on its equals sign giving us an array with the parameter name as the first value and the value of that parameter as the second. (Sometimes, query parameters don’t have an equals sign. We intentionally don’t account for those here, but your application may need to.) We unpack the resulting array and assign it to the variables key and value. That’s a cool new way you can assign individual array values to variables in ES6.

Finally, we add this new key/value pair to the accumulator object. We use square brackets so we can use a variable key name. We assign that key the decoded value. (Values in a URL must be encoded. See Alan Skorkin’s post on URLs. Find the section about special characters. decodeURIComponent will decode the encoded values.)

A Broken Reduction

This code looks pretty good, but it won’t work. A careful read of the reduce documentation reveals the problem:

The accumulator accumulates the callback’s return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied…

Not only do we need to add whatever values we want to the accumulator on each iteration, but we also have to return the accumulator. Since we’re not returning here, the accumulator gets set to undefined on each iteration. The fix is simple:

const queryParams = queryParamsString .split('&') .reduce((accumulator, singleQueryParam) => { const [key, value] = singleQueryParam.split('='); accumulator[key] = decodeURIComponent(value); return accumulator; }, {});

Now, We Have a Handy Query Parameter Object!

If you want greater context for this post, check out my post on using query parameters in your front-end Javascript. It puts everything together and even has a playground app that lets you see query parameters being used on the front-end.

If this post helped you, share your email below and I’ll send you more like it as they go live! Become a better developer by adding useful new tools to your Javascript toolbelt.

If you like this one, you might also be interested in learning to use the Javascript ternary operator. It’s a quick way to make a decision based on a single condition. Works great for assignment!