JavaScript filter() Method
The filter()
method in JavaScript is used to create a new array with all elements that pass a certain condition defined by a callback function. It iterates through each element of the array and invokes the callback function for each element. If the callback function returns true
for an element, that element is included in the new array; otherwise, it is excluded.
Syntax:
arr.filter(function(){
// condition
})
Example: Filtering Array Elements in JavaScript
The code initializes an array arr
with values [2, 4, 8, 10]. The filter()
method is then used to create a new array updatedArr
containing only the elements of arr
that are less than 5. Both the original and filtered arrays are logged to the console.
let arr = [2, 4, 8, 10];
let updatedArr = arr.slice().filter(val => val < 5);
console.log(arr);
console.log(updatedArr);
Output
[ 2, 4, 8, 10 ] [ 2, 4 ]