Skip to main content

JavaScript Array filter Method (Live Playground)

The filter method in JavaScript is used to create a new array from an existing one, including only those elements that satisfy a certain condition.

Here's a simple example:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers);
// Expected output: [2, 4, 6, 8, 10]
Live Playground, Try it Yourself

In this example, we have an array called numbers. We use the filter method to create a new array called evenNumbers which contains only the numbers from the original array that are even. The condition we use to filter the original array is number % 2 === 0, which checks if a number is even.

It's important to remember that the filter method doesn't modify the original array. Instead, it creates a new array with the elements that pass the test you provide.

In conclusion, the filter method is a powerful tool in JavaScript for creating new arrays based on conditions set on elements of an existing array. It's part of JavaScript's suite of array methods that make working with arrays more efficient and expressive.

Remember to practice using filter with different arrays and conditions to get a better understanding of how it works!