/

How to Filter an Array in JavaScript

How to Filter an Array in JavaScript

In JavaScript, filtering an array to get a new array with specific values is a common task. Thankfully, JavaScript arrays provide a built-in method called filter() that makes this process easy and efficient.

Let’s say we have an array called dogs with four objects, each representing a different dog:

1
2
3
4
5
6
const dogs = [
{ name: 'Roger', gender: 'male' },
{ name: 'Syd', gender: 'male' },
{ name: 'Vanille', gender: 'female' },
{ name: 'Luna', gender: 'female' }
];

If we want to filter this array to get only the male dogs, we can use the filter() method. Here’s how:

1
2
3
const maleDogs = dogs.filter((dog) => dog.gender === 'male');

// Result: [{ name: 'Roger', gender: 'male' }, { name: 'Syd', gender: 'male' }]

In the code above, we pass a callback function to the filter() method. This function takes each element of the dogs array as an argument and checks if the gender property is set to 'male'. If the condition is true, the element is included in the resulting maleDogs array.

By using the filter() method, we can easily manipulate arrays and create new arrays that meet our specific criteria.

Tags: JavaScript, array filtering, filter method, JavaScript arrays