Last updated on November 24, 2022
In JavaScript, the filter() method iterates over the values in an array and returns a new array that passes the defined conditions in the method. We have used all possible parameters in the filter() method in the below code snippet.
array.filter(function(value, index, arr), thisValue)
Let’s understand the above code snippet.
Let’s create a numbers array and apply the filter() method to it.
let numbers = [1,-1,2,3,5];
const filtered = numbers.filter((num)=>{
return num >=1;
});
console.log(filtered);
// [object Array] (4)
[1,2,3,5]
In the above example, the arrow function has num as a parameter that checks if the value from the num variable is equivalent to 1 or greater and then returns a new array of only positive numbers.
If we find only negative numbers from the array then our example will be like the one below
let numbers = [1,-1,2,3,5];
const filtered = numbers.filter((num)=>{
return num<1;
});
console.log(filtered);
In the above example, the filter() method checks only the numbers which are less than 1 in this case the new array will consist of negative numbers.
The filter() method allows us to filter values from an array. It has two required and three optional parameters.