filter() in JavaScript


In JavaScript, the filter() method helps to pick specific items from an array based on certain conditions. It creates a new array containing only the ones that match our criteria without changing the original array. If no elements pass the test, the filter method will return an empty array.
Example:
const numbers = [10, 20, 30, 40, 50];
// Filtering even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0); // Output: [10, 20, 30, 40, 50]
// Filtering numbers greater than 30
const greaterThanThirty = numbers.filter(num => num > 30); // Output: [40, 50]
// Filtering numbers greater than Ninty (none in this case)
const greaterThanNinty = numbers.filter((num) => num > 90); // Output: []
Subscribe to my newsletter
Read articles from Dikshya Subedi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
