The JavaScript filter array method

Simeon Kengere
3 min readJul 14, 2022

--

Image credit: scriptverse

The filter method (filter()) creates a new array filled with elements that pass a test provided by a function.

It creates a shallow copy (meaning it does not change/mutate the original array) of a given array that passes a given test provided by a function.

Let us look at an example to understand how the filter array method works. Consider the following array:

The parameters accepted by the filter function are the element of the array, index of the array, and the array itself in that order. Let us pass in those three parameters in the filter array method below to see how the output would look like.

The following would be the output on the console:

As you can see above, the output is in the format of element, index, and array of the array myNumbers. It is also important to note that it is not mandatory to pass all 3 parameters when dealing with the filter array method. Supposing we wanted only the element and index of the array, we would write the code as follows:

And the output on the console would be:

What is important is that we need to remember the order in which we pass the parameters in the function.

Let us now look at a more realistic example on how we can use the filter method. Suppose that from our array, we want all the elements that are less than zero. The following is how we would achieve this:

The output on the console would look like:

Now, the big question arises. Why would we want to use the filter array method over a simpler for…of loop? This is because the filter method supports chaining of other multiple array methods (meaning use of multiple array methods, one after another to build one final result) whereas the simple for…of loop does not support chaining.

Stay tuned for an article on chaining multiple array methods to further appreciate the filter array method over the for loop.

--

--