Bradley Calkins
2 min readJan 7, 2021

--

The Value of Filter

The filter is a valueable applicative function in javascript. This function iterates through each element in an array and executes a conditional function on each element. Then creates a new array in a non-mutative process.

The method in which a filter function enacts its behavior on each element is via a callback function. For comprehension its advisable to look under the hood of the function. The logic is a standard for loop, and for context lets have a look at this bank array example…..

First, we declare an empty array to place the desired elements into this new array. Then to iterate and execute the code we will use the for loop construct. In this case the new array will be the array element that equals the string ‘chase’ from the original array. The callback function is the block of code specifying the condition. When the new array is returned its simply [‘chase’] as this is the only element in the array that matches the condition.

However, writing for loops like this for each time you would like to abstract a new array predicated on a condition is tedious. This is why the filter function is valuable as we can execute an equal abstraction of data with less input. For instance…..

We simply save the filter function to a variable and call the filter function on the banks array. Then return which element we would like to abstract from the original array. The new filteredBanks array prints Chase. So with 1 line of code you are able to arrive at the same conclusion.

--

--