Open In App

What is Filter metod in JavaScript ?

In JavaScript, the filter() method is an array method used to create a new array containing all elements that pass a specified test implemented by the provided callback function. It iterates over each element in the array and applies the callback function to determine whether the element should be included in the filtered array.

Syntax: 

array.filter(callback(element, index, arr), thisValue);

Parameters:

Example: Here, we have an array numbers containing numeric values. We use the filter() method to create a new array containing only the even numbers from the original array. The callback function checks if each element is divisible by 2 without a remainder (element % 2 === 0). Elements that satisfy this condition are included in the evenNumbers array.




const numbers = [1, 2, 3, 4, 5];
 
const evenNumbers = numbers.filter(element => element % 2 === 0);
 
console.log(evenNumbers);

Output
[ 2, 4 ]

Article Tags :