How to Use Filters with Arrays
tanzirulhuda
Posted on October 19, 2022
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
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' }]
Okay! Thanks for reading. Happy coding!
You can follow me:
Twitter
💖 💪 🙅 🚩
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
javascript Evaluating (Historically Optimal) Fantasy F1 Teams with Linear Programming
November 21, 2024