JavaScript .filter( )
Tags: beginners, codenewbie, javascript
Published: 2022-05-09 04:57:18


![header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcofkkw3izkyu968s5mr.png)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.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

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.  

![practice data header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xotx1c1ds9o23b09whng.png)

![Dwight sitting at computer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvbdcsblzrlqdtrrjco6.jpeg)

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"
    }
]
```
![filter() by gender header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6x41gaglna57b146cdcf.png)

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!

![filter() by age header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q0cb81q4bvk6jsl6zm9c.png)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.

![ageBelowForty console.log return showing the new array created with only characters under the age of 40](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrhn6o8eoqwf4ur1d5jf.png) 

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
```


![filter() by age and gender header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtfp9hwfdbkulplwtjcb.png)

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. 

![find() and more header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oo8covv5383noj1gjvn0.png)
- If you need to filter through the array for **one** specific element, try the [.find()] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) method. This method returns the first element that passes as true. 

- Not sure you are working with an array? Check out the [.isArray()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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.

![Dwight sees job description as salesman and looks shocked](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syiwnsmprnzn7ot0uh8m.png)


![Dwight quickly typing on the keyboard changing code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojs7peignfnr4or8s968.gif)

![Code joke, Dwight destructively code changes job to Assistant to the Regional Manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7zn9vzdqhuegqh5toe7.png)

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](https://www.linkedin.com/in/rachelsmithstark/) **&** [GitHub](https://github.com/rstarksmith)

Resources: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [Eloquent Javascript] (https://eloquentjavascript.net/), [w3schools](https://www.w3schools.com/jsref/jsref_filter.asp), [Canva](https://www.canva.com/)          
 
   
    
![filter() header bar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tez4qha78luhjmka1xf2.png)