Tip 23: Pull Out Subsets of Data with filter() and find()
Explore how to simplify data extraction in JavaScript arrays using the filter() method to get subsets of data while preserving structure, and the find() method to retrieve only the first matching element. Understand practical use cases, looping simplification, and improvements in code readability and performance.
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.
You’ll need to check to see if the string contains a form of “Dav” using the
match() method on a string. This method will return an array of information if
the string matches a regular expression matches and null if there’s no match.
In other words, ...