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>
);
});
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.