Reputation: 1693
How to remove the value "nissan", from an array of objects?
const cars = [
{type: "audi", amount: 2},
{type: "nissan", amount: 12},
{type: "mazda", amount: 5},
{type: "volvo", amount: 5}
]
This is how I display all the types and amounts:
cars.map(car => {
return (
<div>{car.type}: {car.amount}</div>
);
});
But I would like to remove the value "nissan", before mapping over the cars, how could I do that with .filter?
removeNissan() {
// cars.type !== "nissan"
}
cars.filter(removeNissan).map(car => {
return (
<div>{car.type}: {car.amount}</div>
);
});
Upvotes: 0
Views: 61
Reputation: 68665
Use Array#filter function before map
function
const cars = [
{type: "audi", amount: 2},
{type: "nissan", amount: 12},
{type: "mazda", amount: 5},
{type: "volvo", amount: 5}
]
cars.filter(item => item.type !== 'nissan').map(car => {
return (
<div>{car.type}: {car.amount}</div>
);
});
Or if you want to use a named function, declare your function
removeNissan(car) {
return car.type !== "nissan";
}
filter will pass the each item as argument to the function.
Upvotes: 1