Javascript array filter
How to filter list of elements in array which meet the given conditions in Javascript?
// Array of object
const cars = [
{make: 'Ford', model: 'Mondeo', gearbox: 'manual'},
{make: 'VW', model: 'Passat', gearbox: 'automatic'},
{make: 'Volvo', model: 'XC90', gearbox: 'automatic'}
]
// Filter the list of cars for those with automatic gearbox
const automatic = cars.filter(function(car) {
return car.gearbox == 'automatic'
});
console.table(automatic);
ES6 syntax for filter()
// Array of object
const cars = [
{make: 'Ford', model: 'Mondeo', gearbox: 'manual'},
{make: 'VW', model: 'Passat', gearbox: 'automatic'},
{make: 'Volvo', model: 'XC90', gearbox: 'automatic'}
]
// Filter the list of cars for those with automatic gearbox
const automatic = cars.filter(car => (car.gearbox == 'automatic'));
console.table(automatic);
Output in both cases is the same
| make | model | gearbox |
| "VW" | "Passat" | "automatic" |
| "Volvo" | "XC90" | "automatic" |
You can check it here: http://codepen.io/mslepko/pen/EZbXjv