Open In App

What is Filter metod in JavaScript ?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • callback: This parameter holds the function to be called for each element of the array.
  • element: The parameter holds the value of the elements being processed currently.
  • index: This parameter is optional, it holds the index of the current element in the array starting from 0.
  • arr: This parameter is optional, it holds the complete array on which Array.every is called.
  • thisValue: This parameter is optional, it holds the context to be passed as this is to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.

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.

Javascript




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


Output

[ 2, 4 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads