JavaScript, how to filter an array
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
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025