How to use filter() Method in JavaScript?

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.

  • The filter() method is attached to the array to filter the values in the array.
  • The first parameter value is the current element that needs to be filtered.
  • The index is optional and can start the iteration from a specific index. For example, filtration should start from the 3rd index.
  • arr returns the current item’s array. It means it will give you a full array of the item.

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.

Conclusion

The filter() method allows us to filter values from an array. It has two required and three optional parameters.