The filter()
method in JavaScript is used to create a new array with all the elements that pass the test implemented by the provided function.
The syntax of the filter()
method is as follows:
carray.filter(callback(element[, index[, array]])[, thisArg])
Here, array
is the array to be filtered, and callback
is the function that is used to test each element of the array. The callback
function takes three arguments:
element
: The current element being processed in the array.index
(optional): The index of the current element being processed in the array.array
(optional): The array on whichfilter()
was called.
The thisArg
parameter is optional and represents the this
value for the callback function.
The filter()
method creates a new array with all the elements that pass the test implemented by the callback
function. The elements that fail the test are excluded from the new array.
For example, let's say we have an array of numbers:
javascriptconst numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
We can use the filter()
method to create a new array that contains only the even numbers from the original array:
typescriptconst evenNumbers = numbers.filter(number => number % 2 === 0);
In this example, the callback
function tests each element of the numbers
array to see if it is even (number % 2 === 0
). If an element passes the test, it is included in the new evenNumbers
array. The result of the filter()
method is [2, 4, 6, 8, 10]
.
Comments
Post a Comment