#100DaysOfCode Day 9: Filter & Find

Shawn McMahon
3 min readJul 20, 2021

Day 9: Array Iterator Methods: Filter & Find

Today I am continuing my series on array iterator methods. Yesterday I talked about forEach and Map. Today I am going to reflect on two more iterator methods: Filter & Find.

Source: https://www.pexels.com/photo/photo-of-cryptic-character-codes-7319085/

Do you have a massive dataset? Do you need to make a new array with only certain types of data? Is your new array going to be a different length from your original dataset? Filter may be what you are looking for.

Filter will take in an array as an input. Inside the filter function, we can write any logic to filter out the data we are looking for. Filter will search the original array index by index and evaluate the current index through this logic. Filter is looking to return a boolean expression for each index under the hood. If the logic in the current index evaluates to true, Filter will push that index into the new array. If the logic is false, Filter will ignore that index and move onto the next one.

Find is very similar to Filter. It has two main differences. The first difference is that Find will search the array for the first index that evaluates to true. Once that first index with a true expression is found, Find will stop completely and return data inside that index. The second difference is that find does not return an array. Since Find will only return the data from this 1 index, there is no point in returning that one data point inside an array. So Find will return whatever data type is inside the first index that evaluates to true.

Consider my example above. We have an array of random words. We want to take out only words that include the string ‘op’. In this case, an includes() is the fastest way to get what we need. If we use that logic inside of a filter method, it returns all words in the randomWords array that include ‘op’. In this case, this is Pop, Stop, and Cop.

If we use the exact same logic but replace Filter with Find, you see it only returns the first word in the array that satisfies that condition. Also notice, we only see a string — not an array!

Tomorrow we will talk about my favorite iterator method — reduce!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shawn McMahon
Shawn McMahon

Written by Shawn McMahon

Software Engineer, Snowboarder, Music Enthusiast

No responses yet

Write a response