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 that only contains some values of the original array.

How can you do this?

JavaScript array built-infilter()The methods we can use for this task.

Suppose we have an array containing 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 just want to filter male dogs.

You can do this in the following ways:

const maleDogs = dogs.filter((dog) => dog.gender === 'male')

// [ { name: ‘Roger’, gender: ‘male’ }, { name: ‘Syd’, gender: ‘male’ } ]

Download mine for freeJavaScript beginner's manual


More js tutorials: