The filter
function in the Underscore library allows you to filter an array of elements based on a provided condition. Here's an example of how to use it:
index.tsx481 chars16 lines
In this example, we first load the Underscore library using require()
. Then, we create an array of numbers called myArray
.
To filter this array, we call the _.filter()
function and pass in the array as the first argument. The second argument is a function that defines the condition for filtering. In this case, we only want the even numbers to be included in the new array, so we use the modulo operator %
to check if num
is divisible by 2.
The filtered array is returned and stored in a new variable called filteredArray
. We then log this array to the console, which should output [2, 4]
.
You can use any condition you want inside the filtering function, and you can also use arrow functions to make the code more concise.
gistlibby LogSnag