How to Use Filters with Arrays

tanzirulhuda

tanzirulhuda

Posted on October 19, 2022

How to Use Filters with Arrays

Filtering an array is useful when you’re working with multiple columns of corresponding data. In this case, you can include and exclude data based on any characteristic that describes a group in your array.
To filter an array, use the filter() function.
Example snippet:

const cars = [
  { make: 'Opel', class: 'Regular' },
  { make: 'Bugatti', class: 'Supercar' },
  { make: 'Ferrari', class: 'Supercar' },
  { make: 'Ford', class: 'Regular' },
  { make: 'Honda', class: 'Regular' },
]
const supercar = cars.filter(car => car.class === 'Supercar');
console.table(supercar); // returns the supercar class data in a table format
Enter fullscreen mode Exit fullscreen mode

You can also use filter() together with Boolean to remove all null or undefined values from your array.

Example snippet:

const cars = [
  { make: 'Opel', class: 'Regular' },
  null,
  undefined
]

cars.filter(Boolean); // returns [{ make: 'Opel', class: 'Regular' }] 
Enter fullscreen mode Exit fullscreen mode

Okay! Thanks for reading. Happy coding!
You can follow me:
Twitter

💖 💪 🙅 🚩
tanzirulhuda
tanzirulhuda

Posted on October 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related