The filter()
method in JavaScript is used to create a new array with all the elements that pass a certain condition. It takes a callback function as its argument and applies that function to each element of the array.
Here is the syntax for using filter()
:
index.tsx49 chars2 lines
The callbackFunction
takes three arguments:
element
(required): The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The array on which filter()
was called.The callbackFunction
should return true
or false
. If it returns true
, the element is included in the new array, otherwise, it is skipped.
Here's an example that demonstrates the usage of filter()
:
index.tsx161 chars8 lines
In this example, filter()
is used to create a new array evenNumbers
that contains only the even numbers from the numbers
array.
Note that filter()
does not modify the original array. It returns a new array.
I hope this helps!
gistlibby LogSnag