Today, we’re going to look at the filter() method, which will create a new array from the arguments sent to it that contain only the elements that pass the test the filter() method is written to perform. That’s a mouthful, so I think looking at MDN’s examples will make it clearer than reading that sentence.
First, the syntax of the filter() method according to MDN:
Okay, that’s perfectly clear.
Anyway, looking at the above, we can see that there are two parameters for the filter() method. First is the callback, and this is basically the test you’ll perform to “filter” the items you want out of the arguments. It will be written as a function, with the arguments element – the element it is currently working on, index – the index of the element it is currently working on, and array, which is the array it’s processing. Finally, if the element passes the test, true is returned, and if not, false is returned. If the element doesn’t have a value assigned to it or doesn’t exist, then it’s skipped.
Second is an optional parameter, thisArg, which MDN defines as “Optional. Value to use as this when executing callback.” The this parameter is a whole other blog post or three unto itself, so I’m not going to do much with this one for this post!
As with the slice method we talked about, the original array isn’t modified. Also, if any changes are made to the original array AFTER filter() is called like changing, adding, or deleting an element, the output of filter() doesn’t change with it. You’d have to run filter() again.
Now, let’s take a look at MDN’s example. We want to “filter” out all the elements in an array that are less than 10 and only keep the ones that are greater than or equal to 10. Here’s their code:
The first line calls the filter() method, passing the arguments under the variable value. The second line returns the elements only if they are greater than or equal to 10. To call this function, we use the following line of code:
So what we’re doing is calling a filter method isBigEnough, passing it the array [12, 5, 8, 130, 44], and assigning the result of the filtering to the variable filtered. Our output is:
[12, 130, 44]
which is all the elements meeting the condition. The ones that do not – 5 and 8, are “filtered” out.
Note that the last four elements don’t meet the criteria. Now, here’s the filter code:
First, we create a variable called invalidEntries that acts as a counter. We do this outside the function so it’s a global variable (review the concept of scope if you don’t know what this means). Next we declare the function filterByID and pass it the argument obj. Inside the function we have an if-then statement. If we have an ID in the Object, and that id is a number, and if that id is not -not-a-number (yes, that’s torturous) then return true, otherwise increment invalidEntries because the element doesn’t meet any of the criteria and return false.