Skip to main content

Mapping and Filtering Arrays in JavaScript

In this article we will delve into the map() and filter() array methods available in JavaScript. We will understand their properties, explore a few use-cases, and discuss how they lend to the "functional" aspect of the programming language. We will also write our own implementations of these functions, just to gain a better understanding of how they work under the hood.

Properties of map() and filter()

Unlike methods like push() or fill(), both map() and filter() work on a copy of the input array. They can thus be said to be immutable. This means they do not modify array elements themselves, rather return a new array after processing the original.
These methods are also pure functions, meaning their output depends solely on the input arguments and not on any external side effects.

Working with Array.prototype.map()

The map function operates on arrays and takes exactly one parameter, that being the callback function invoked on each element.

As you can see, the callback function takes in each element of the array, one at a time, and returns a modified version of it. The map function then collects all modified elements and returns this modified array. 

More importantly, the original array remains unchanged.

Here's an example use-case for map(). Say we have an array of user IDs in our website and want to get a corresponding array of user names. Using traditional loops, our code would look something like
However, using the map() function makes things much simpler, as shown
Note that you can pass any type of function to map(), although arrow functions are preferred for simple mappings owing to their syntactic sugar.

Working with Array.prototype.filter()

Similar to map(), the filter function takes a single argument: a callback function that is invoked on each element of the array being operated on.

However, unlike the callback function used by map(), the function in filter() must return a truthy value if the element is to be retained in the array.

Building on the example above, say we wished to filter out users whose IDs were odd. We can use the filter() method as shown to accomplish this:
If the user ID is even, we do not return anything. Implicitly, this is the same as returning undefined, which JavaScript considers to be a falsy value, hence discarding the array item.

Combining map() and filter()

The real power of these two functions is realised when they are used together. Because they each return new arrays, we can chain them to operate on the returned array and perform complex tasks. This is known as pipelining.

A good example of a pipeline would be to convert our user ID array to an array of user names of those users who have odd numbered IDs.
To do this, we would first need to filter the array and retain only odd numbered IDs, and then map over this new array to get the user names.
This is much simpler than having to write multiple loops that iterate over your arrays. In fact, you can chain as many function calls as you wish to get data in the format you need.

Implementing map() and filter()

We know that map() and filter() operate on an array, take in a callback as a parameter, and return a new array. We can easily implement both of them as:

Conclusion

map() and filter() are great utilities when you're working with arrays and want to write clean, sequential, and readable code. Pipelining can be used to further simplify how you format data, and the immutable characteristics of these functions makes it easy to debug your JavaScript programs. 

Make sure to follow the blog if you want more nifty guides and programming hacks!

Comments

Popular posts from this blog

Making Custom Dashed Borders with CSS

The CSS   border  property is great for adding stroke outlines to your elements, but it offers little flexibility when working with dashed borders. For example, you can't customise dash lengths, gaps between dashes, or even the caps on each dash.  To overcome this,  we'll be writing our own dashed border renderer using the new CSS Houdini Paint API . The full code is available at the end of the post and on GitHub here . Final result Note that as of 2021, the Paint API is not supported by Firefox or Safari, so if this feature is mission-critical to your project in these browsers, you might want to look for alternatives. Support tables for the API can be found  here . Writing a Custom Paint Class To start with, we need to create a class that handles all the custom painting we'll be doing. It will be responsible for exposing available properties and drawing the actual borders themselves. As you can see, the class has a method that returns all properties we'd like t...