Reputation: 9859
Is it's possible to remove object from array by it's value, not by index without iteration with for
loop?
I tried to remove element with iteration, but it's look like that it do not remove iteration elements:
App.$refs.userContent.foo : [1,2,3,4]
console.log(App.$refs.userContent.foo);
App.$refs.userContent.foo.forEach(function(x,i)
{
App.$refs.userContent.foo.$remove(i);
});
console.log(App.$refs.userContent.foo);
Result:
[1, 2, 3, 4, __ob__: Observer]
[3, 4, __ob__: Observer]
Why it's do not remove all elements?
Upvotes: 0
Views: 6956
Reputation: 5927
As you're removing elements from the array, you're changing the index of the ones that remain. If you wanted to remove all the elements, you'd do the following inside your .forEach() :
// Keep removing first array element until they're all gone
App.$refs.userContent.foo.$remove(0);
...but that would be strange to empty an array.
To answer your original question - No. You cannot remove an array element by its value in one step. You first have to find the index of the element, and then remove it by index. In vanilla JS, you can use .splice() to remove an element by its index:
// Remove 4th element from array
myArray.splice(3, 1);
Upvotes: 1
Reputation: 32921
In Vue 1 there's a $remove
method on arrays where that you can pass a reference to.
this.items.$remove(item)
I think that's gone in Vue 2 though. You can use indexOf
instead of looping through. Something like:
var index = this.items.indexOf(item);
if (index > -1) {
this.items.splice(index, 1)
}
Upvotes: 0
Reputation: 232
It has to iterate the array to find the element you want removed by value. So the answer is no.
You may be able to trick it into deceiving you about how it is doing this, but ultimately it will still have to find the element with the value you want removed. There are methods to optimize the search though if the array is sorted.
Upvotes: 0
Reputation: 1084
You may want to use the filter function. For example:
[1,2,3,4].filter(x => x != 2)
to remove item from the array whose value is 2.
Upvotes: 0