Consider the following data:
food = {
id: 1,
name: 'Pizza',
price: 16
};
orders = [
{ food_id: 2, table_id: 5 },
{ food_id: 2, table_id: 5 },
{ food_id: 1, table_id: 5 },
{ food_id: 3, table_id: 5 },
{ food_id: 1, table_id: 5 }
];
I want to remove a single item from the orders array matching food_id
. Here's what I tried:
removeFoodOrder(food: Food): void {
for (let order of this.orders) {
let match = this.orders.filter((order) => order.food_id == food.id);
match ? this.orders.splice(this.orders.indexOf(order), 1) : null;
break;
}
console.log(this.orders);
}
If I call removeFoodOrder(food)
, it removes the first element from the array no matter what food item I pass in the params.
removeFoodOrder(food)
// removes {food_id: 2, table_id: 5} (the first element)
// I want to remove {food_id: 1, table_id: 5},
I want to target the matching element from the array and remove a single instance of it. Where did I go wrong?
1) Remove duplicates from an array using a Set To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.
The Array findIndex() and splice() Methods To remove an element from an array by ID in JavaScript, use the findIndex() method to find the index of the object with the ID in the array. Then call the splice() method on the array, passing this index and 1 as arguments to remove the object from the array.
You could use Array#filter
method:
food = {
id: 1,
name: 'Pizza',
price: 16
};
orders = [
{ food_id: 2, table_id: 5 },
{ food_id: 2, table_id: 5 },
{ food_id: 1, table_id: 5 },
{ food_id: 3, table_id: 5 },
{ food_id: 1, table_id: 5 }
];
removeFoodOrder(food: Food): void {
this.orders = this.orders.filter(({ food_id }) => food_id !== food.id);
}
Edit:
Since your array allows duplicate elements and you want to remove only the first match, you could use the Array#findIndex
+ Array#filter
methods:
const foundIndex = this.orders.findIndex(({ food_id }) => food_id === food.id);
this.orders = this.orders.filter((_, index) => index !== foundIndex);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With