Filter an Array with JavaScript

A practical tutorial on how to filter arrays in JavaScript using the Array Filter method.

Filter an array using the Array Filter Method

In JavaScript, all arrays have a filter method that you can use in your programs. This built-in method creates a new array based on your instructions. You will give these instructions as a parameter of the filter method. Each time the filter method iterates on the array, it will call your function.

const colors = ['blue', 'yellow', 'red', 'green', 'yellow', 'red', 'blue']
const yellowArray = colors.filter((color) => color === 'yellow')

console.log(yellowArray)
// Output: ['yellow', 'yellow']

Create your own function to filter an array

If you want to understand better how the filter method works, you can create your own function. Let's take the example above, but we will replace the second line with our function call.

function filter(arrayToFilter, elementToFilter) {
  const newArray = []

  for (const element of arrayToFilter) {
    if (element === elementToFilter) newArray.push(element)
  }

  return newArray
}

const colors = ['blue', 'yellow', 'red', 'green', 'yellow', 'red', 'blue']
const yellowArray = filter(colors, 'yellow')

console.log(yellowArray)
// Output: ['yellow', 'yellow']

As you can see, if you want only to compare strings or numbers, you can re-create this function pretty fast!

Filter an array of objects using the Array Filter Method

If you want to filter an array of objects, you can still use the built-in method. The only difference will be in the comparison. You will need to select the object property value to compare.

In the example below, we now have books. Each book is an object and has a color property. As in the previous parts, we want to create a new array for yellow books.

Let's see how we can do that!

const books = [
  { name: "You don't know JS", color: 'yellow' },
  { name: 'Eloquent JavaScript', color: 'yellow' },
  { name: 'JavaScript: The Definitive Guide', color: 'white' },
]
const yellowBooksArray = books.filter((book) => book.color === 'yellow')

console.log(yellowBooksArray)
// Output: [
//  { name: "You don't know JS", color: 'yellow' },
//  { name: 'Eloquent JavaScript', color: 'yellow' },
//]

➡️ If you want more content like this, you can follow me on Twitter, where I tweet about web development, self-improvement, and my journey as a fullstack developer!

Learn to code with simple and concrete examples.

English / Français