Using .filter() in JavaScript for Beginners

Wesley Beck
5 min readMar 24, 2021

A common problem I had when first learning JS (and still struggle with at times) is seeing the bigger picture with using collection processing methods like .filter(), .sort(), .some(), of a few to name. My issue is/was thinking up a callback function or expression that returns a Boolean value(true/false) that needs to be passed into the collection processing method in order to produce the certain result you want. So this little blurb is going to cover a basic grounds of what to look for in setting up the .filter() method specifically as an example but this works with the other afore mentioned processing methods above with some differences based on how the function operates and the end result.

Let’s say we have an array of numbers/integers we want to filter:

const numberArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And let’s filter out all the odd numbers (the numbers we want back should be even numbers). We use the characteristic that all even numbers can be divided by 2 without having a remainder to evaluate each element in the array. To start, we will set up a simple .filter() method. Filter works exactly how it sounds; It “filters” out the elements you want from an array and returns a new array with those elements that evaluate to true in your test. In my example, I use a comparator to determine whether that comparison returns true or false, but you can use if/else statements within your .filter() depending on the data you are processing. The important thing to note: Always use some sort of evaluation/callback function in your .filter() method that return Boolean values in order to get that item filtered out of the array. I will demonstrate what I mean by this below using the numberArr variable I created for this example.

const numberArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]let evenNumbers = numberArr.filter(n => {return n % 2 === 0})/*calling the evenNumbers variable in console will result in a new array with all the even numbers:*/
example from dev tools console using Google Chrome

An in depth overview of what’s happening: When .filter() is invoked, it iterates over each element in the array (as any usual collection processing method) and verifies whether the function passed into .filter() evaluates to true and keeps that element, or false and ditches that element, so to speak. In this case, we use the modulo(checks the remainder value on something divided by a set integer) operator and set the remainder value as comparing it to 0 ({n % 2 ===0}). So, when we iterate over the first element, the evaluation n becomes 1(n is just a place holder for the element we pass into the iterator) which results in the return of false because when you divide 1 by 2 it results in a decimal or fraction (aka a remainder > 0) and thus results in the comparison 1 % 2 === 0. So, the first element, 1, is left out of the new array. The next element, 2, is passed into the callback function and evaluated. Because 2 divided by 2 results in 1 with no remainders the modulo evaluation results in a true return on that element. Thus, the second element (value of 2) in this case is added to the new array. This occurs with each element in the array until all elements have been passed into the comparison function and evaluated. Something to note, which is where I get confused at times, is that the .filter array doesn’t return the evaluations, but rather the elements and their values even though the comparison function returns true/false. So instead of getting an array back of [false, true, false, true, false,…] we actually get the elements that return true on the comparison(something to watch out for). So the result [2, 4, 6, 8, 10] are all divisible 2 and have 0 remainders as well(i.e. even numbers).

Now, objects you have to be a little more careful with because objects can’t be filtered by any characteristic outside of being an object. You have to create a comparison function on a common attribute that all the objects share inside the .filter().

My example for object filter:

const graphPlots = [ {x: 1, y: 2}, {x: 5, y: 2}, {x: 2, y: 1} ]graphPlots.filter( obj => { return obj.y === 2} )

Result of the above line of code:

When using objects make sure to make a comparison function around the attribute they have in order to filter. Notice how I use obj.y in the comparison function. If you forget to call on the objects’ specific attribute, call on a nonexistent attribute(maybe a typo), or call on the object itself, .filter() will return an empty array:

.filter() is just one of many collection processing methods that use comparison functions returning Boolean values to filter out certain elements that do not coerce true values from such comparisons. When beginning to learn about these collection processing methods checkout the MDN documentation as they provide clear examples and descriptions, which I have listed at the end of this blog.

Important things to look out for when using just starting out with collection processing methods in general:

1 — Does the original array get modified by the processing method? If so, code accordingly.

2 — What kind of evaluation/function needs to be passed in to return the proper data or objects you want returned back? ( how .filter() uses a Boolean comparison to determine what should be added to the new array from the current array being evaluated)

I hope this shed’s some light on using .filter() and incorporating the same type of usage with other functions I briefly mentioned in the introduction. Below I listed the MDN documentations links to get a better look at some of the other common collection processing methods that you might see or want to use on a future project. Hope you enjoyed my simple tutorial. I just wanted to share my basic understanding for any beginners out there new to JavaScript that are struggling or have struggled with understanding these types of collection processing methods. If you have any other tips for beginners, please leave a comment of good tips for beginners just getting started in JavaScript! It woul be great to see some new advice for beginners as well as experienced developers. Happy Coding!

MDN documentation linked here:

.filter()

.sort()

.some()

--

--

Wesley Beck

Recent Flatiron Boot Camp Grad. Pursuing my dream to become a software engineer, sharing what I can to help others that are new to coding.