JavaScript, how to filter an array
New Courses Coming Soon
Join the waiting lists
How to filter an array in JavaScript
You have an array, and you want to filter it to get a new array with just some of the values of the original array.
How can you do so?
JavaScript arrays come with a built-in filter()
method that we can use for this task.
Say we have an array with 4 objects representing 4 dogs:
const dogs = [
{
name: 'Roger',
gender: 'male'
},
{
name: 'Syd',
gender: 'male'
},
{
name: 'Vanille',
gender: 'female'
},
{
name: 'Luna',
gender: 'female'
}
]
and you want to filter the male dogs only.
You can do so in this way:
const maleDogs = dogs.filter((dog) => dog.gender === 'male')
// [ { name: 'Roger', gender: 'male' }, { name: 'Syd', gender: 'male' } ]
→ Get my JavaScript Beginner's Handbook
→ Read my
JavaScript Tutorials
on The Valley of Code
→ Read my
TypeScript Tutorial
on The Valley of Code
Here is how can I help you:
- COURSES where I teach everything I know
- CODING BOOTCAMP cohort course - next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- Follow me on X