JavaScript .filter( )
Rachel Stark
Posted on May 9, 2022
There is a wealth of information and videos on how to apply the filter() method, but as we know, the best learning comes from coding along and experimenting on our own. So let's dive in...
const newArray = array.filter(function(element) {
return //conditional statement
})
console.log(newArray)
//=> returns array with filtered elements
The filter() method takes a callback function containing search criteria used to filter through the target array. Each element of the target array is passed through the callback function looking for a truthy value and then a new array of elements that proved true is returned. If no elements pass as true, then filter() will return an empty array. This method is non-destructive because it does not mutate the original array.
Some optional parameters for this method are index (if you want to start the iteration from a specific point in the array) and thisArg, which you can read about here.
Using the same syntax as above, let's write in a simple conditional statement.
const myArray = [ 3, 2, 1, "go", 1]
const numArray = myArray.filter(function(element){
return element > 1
})
console.log(numArray)
//=> [3, 2]
That was easy, right? There are easier/cleaner ways to code this but for learning purposes, I like seeing details! Next up is some data you can use to follow along or create some of your own filter() code.
If you told me one day I would be typing out The Office's character data to practice coding, I would have laughed, but here I am!! And yes, I did find that some fans had calculated character ages based on random bits of information in the show.
const officeCharacters = [
{
character: "Michael Scott",
gender: "male",
age: 40,
job: "Branch Manager"
},
{
character: "Dwight Schrute",
gender: "male",
age: 35,
job: "Salesman"
},
{
character: "Pam Beesly",
gender: "female",
age: 26,
job: "Receptionist"
},
{
character: "Jim Halpert",
gender: "male",
age: 26,
job: "Salesman"
}
]
Keeping the same syntax as above we want to return an array of male characters only by filtering through the characters gender values. Since the data provided is an array of objects, we will need use dot notation to access the keys' values.
const maleCharacters = officeCharacters.filter(function(char) {
return char.gender === "male"
})
console.log(maleCharacters)
//=> returns new array with only the male characters
Sorry, Pam!
Now let's filter characters under the age of 40. This time using an arrow function and setting the condition to less than or equal to 39.
const ageBelowForty = officeCharacters.filter(char => char.age <= 39)
console.log(ageBelowForty)
Here we see the returned array ageBelowForty in the browser console.
If you're anything like me.. you're probably thinking age and gender are not really the best filters for employees so here is one more, same idea but filtering job position..
const salesEmployees = officeCharacters.filter(char => char.job === "Salesman")
console.log(salesEmployees)
//=> returns array of 2 salesman
What about multiple conditions? YES. Let's give it a go..
const filterCharacters = officeCharacters.filter(char => {
return char.age >= 30 && char.gender === "male"
})
console.log(filterCharacters)
//=> returns an array of 2 characters (Michael and Dwight)
Say we are not sure what we are looking for but know what we don't want. Try out the !== operator.
This is just a simplified start to filter. Can you imagine how handy this is for large arrays of objects? There are many different ways to write conditionals making .filter() a good JavaScript BFF.
If you need to filter through the array for one specific element, try the .find() method. This method returns the first element that passes as true.
Not sure you are working with an array? Check out the .isArray() method on MDN. The .filter() method works only on arrays (including arrays of objects like above) and it will throw an error message if not applied correctly.
I know "salesman" is out-dated and should be sales representative, but that is the job title used in the show. IYKYK
You can connect with me on LinkedIn & GitHub
Resources: MDN, Eloquent Javascript, w3schools, Canva
Posted on May 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 10, 2023