|

How Does The Filter Function Work In Underscore JS?

underscore filter

In Underscore, the filter function provides the ability to filter out some values based off of a Tester function that you pass it. The Tester function is more formally declared as the predicate. The concept is similar to many of the Underscore functions we have covered so far. The official signature of filter is _.filter(list, predicate, [context]) and it returns an array with all the items from the list collection that satisfy the test condition found in the predicate function.



Integer Array

In this first example we have a collection of integer values holding various numbers between 10 and 100. We also have the evenTester, oddTester, greaterThan75, and lessThan50 predicate functions defined. Like many other Underscore functions, we call the main function, in this case filter, and pass the list of values as the first parameter and the predicate function as the second parameter. In fact, you could create an entire library of these different predicate testing functions and use them as you may see fit. When you click to run the example code here, we can see that we have filtered out all of the values that do not match the provided Tester function. The result is a list of Even numbers, Odd numbers, Numbers greater than 75, and less than 55.

Click Clear


Object Array

This second example will test out the filter function using an Object Array. Again we have set up an array of values and this time around we have bicycle, model, and price. After this we have set up our testing, or predicate, functions to do the work for us. The main difference from the integer array example is that since we have an object array, we need to know which property of the object will be used in the testing function. In looking at the evenTester function, we can see that we tap into value.price instead of just the value that’s coming into the function. Pretty much everythig else works in a similar manner. The testing functions are a little bit different, only in that we are using different criteria for testing.

Click Clear


How Does The Filter Function Work In Underscore JS Summary

This tutorial covered the filter function in the Underscore JS Library. We learned that the filter function gives us the ability to filter out some values based off of a Tester or Predicate function that we pass to it. To examine how this works, we set up two examples of working with filter. The first made use of a simple integer array, while the second dove into using filter with an object array.