DEV Community

tanzirulhuda
tanzirulhuda

Posted on

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

Top comments (1)

Collapse
 
alexmustiere profile image
Alex Mustiere

filter with Boolean eliminates any value considered as false, or "falsy" in JS.
For exemple, in your "cars" array, if you add a 0 (zéro) or a '' (empty string) entry, they won't be kept with the "cars.filter(Boolean)" instruction.