
What is _.filter() function in JavaScript
Lets take a look how _.filter() works
27 April, 2022
14
14
1
Contributors
What is _.filter()
_.filter() is a function and it is a part of underscore.js library.
It takes an array and a callback function as its parameter and returns a new array similar to _.map() but it will only store those values in a new array and callback function will return true.
So callback function has to be Boolean for values on which callback function will return true will be pushed into new array and rest will be skipped.
Here is what syntax will look like.
What's the difference between _.filter() and _.map()
So, the common thing is both functions return a new array but the difference lies in the logic of execution behind it. Let's see
•
_.map() returns a new array of same length as the original array that is passed as a parameter.
•
But _.filter() return a new array basis on when the callback function will return true. So the length of the array may vary from the original array its can be shorter, equal or maybe empty.
Execution of _.filter()
Now let's see some examples to see _.filter() in action and its use cases.
Output will be
returning even numbers using _.filter()
That's all folks for today.
See ya.
#javascript
#21daysofupdates