Tip 23: Pull Out Subsets of Data with filter() and find()

In this tip, you’ll learn how to change the size of an array while retaining the shape of the items.

filter()

In the previous tip, you created a new array by pulling out only the relevant information from the original array. You’ll likely encounter situations where you want to keep the shape of the data, but you only want a subset of the total items. Maybe you only want users that live in a certain city, but you still need all their information. The array method filter() will perform this exact action. Unlike the map() method, you aren’t changing any information in the array—you’re just reducing what you get back.

Example: Filtering names in an array

As an example, let’s filter a simple array of strings. You have a team of people, and you want only people named some form of Dave (David, Davis, Davina, and so on). In my hometown, there’s a sandwich shop that gives out a free sandwich once a year to anyone named Joe/Joseph/Joanna, so being able to filter people by name variant is a crucial task. You wouldn’t want to deprive your Daves or Joes of a delicious lunch.

Start with a list of coworkers that you want to reduce down.

Get hands-on with 1200+ tech skills courses.