JavaScript filter(callback) method
The filter()
method in JavaScript creates a new array containing all the elements of the original array that pass a test implemented by a provided callback function. It is a powerful tool for selecting elements based on specific criteria.
Syntax:
callback
: A function that is called for each element in the array. It can accept up to three parameters:currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The arrayfilter()
was called upon.
thisArg
(optional): A value to use asthis
when executing the callback function.
Return Value:
- A new array containing all the elements that pass the test implemented by the
callback
function. If no elements pass the test, an empty array is returned.
Key Points:
- Does not modify the original array: The
filter()
method creates a new array and does not change the original array. - Works with all array elements: It processes each element in the order they appear in the array.
- Returns a new array: Only includes elements that satisfy the condition defined in the
callback
function.
Example 1: Basic usage
Example 2: Using arrow function
Example 3: Using index and array parameters
Example 4: Chaining with other array methods
Example 5: Using thisArg
Summary:
- The
filter()
method is a powerful way to create a new array containing only those elements that meet specific criteria. - It allows for clean, readable code and supports functional programming patterns in JavaScript.
- Since
filter()
returns a new array, it is useful for data selection and manipulation while preserving the original array.