Underscore.js _.filter()
Underscore.js _.filter() is used to filter elements from a list that match certain condition.
The full function signature is _.filter(list, predicate, [context]).
The second function parameter “predicate” is a function that provides the filter logic.
The following example filters even numbers from an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script> <script type="text/javascript"> var numbers = [1,2,3,4,5,6,7,8,9,10]; var even_numbers = _.filter(numbers,function(n){ return n % 2 == 0; }); console.log(even_numbers); </script> </head> </html> |
Output :
Similarly, following example filters employees whose above is 30 using the _.filter() function and then iterates them using _.each() :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script> <script type="text/javascript"> var employees = [{name:"Andy", age:21}, {name:"Bob", age:31}, {name:"Charlie", age:41}]; var emp_above30 = _.filter(employees,function(emp){ return emp.age > 30; }); console.log("Employees above 30 are : "); _.each(emp_above30,function(emp,index){ console.log(emp.name); }); </script> </head> </html> |
Output :
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post