DEV Community

Cover image for How to Filter an Array with JavaScript ☕
Gaël Thomas for HereWeCode

Posted on • Edited on • Originally published at herewecode.io

How to 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']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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' },
//]
Enter fullscreen mode Exit fullscreen mode

Thanks for reading until here!

I hope you learned from it! 🎉

I'm starting to tweet more consistently! If you want to get more tips and resources about web programming -> Find me on Twitter 🐦

Top comments (0)