By Michael Williams, Published on 04/26/2018
Using the filter() method is a quick way to take all of the items from one array that match a criteria and move them to another.
In this example. Lets assume that we have an array of cars and only want to display those which are black.
const cars = [
{ id: 1, make: 'BMW', model: 'Alpina B7', color: 'Black' },
{ id: 2, make: 'BMW', model: 'i8', color: 'White' },
{ id: 3, make: 'Tesla', model: 'Model X', color: 'Blue' },
{ id: 4, make: 'Honda', model: 'Civic', color: 'Black' }
];
const blackCars = cars.filter(car => car.color === 'Black');
If we were to console.log() the results. We would be left with:
console.log(blackCars);
[
{"id":1,"make":"BMW","model":"Alpina B7","color":"Black"},
{"id":4,"make":"Honda","model":"Civic","color":"Black"}
]
This is a quick one liner that is readable.