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?
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);
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.
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.
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)
}
I had the same problem, i fix it putting :key in the v-for
Related
I have a simple array as
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I need to remove the first index from this array and it should be of below type
[{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I tried splice as below
arr.splice(1,1)
But it is giving response {"name":"ram","value":"2"}
how to get [{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
It might be very simple question but Im stuck here from sometime.can someone plz help
I think you taking the returning value of Array.prototype.splice().
Array.prototype.splice() returns an array containing the deleted elements.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
arr.splice(1,1)
console.log(arr);
You can compare the difference methods. Be aware if you need change the array or just get a copy to keep with the original one.
Attention: The first array index is 0, not 1. The index one is the second element of the array
The splice method return the element removed from array. That's the reason why you've got the second element from array in your test
Doc: https://bytearcher.com/articles/how-to-delete-value-from-array/
In your question you got the second index that is 1, in order to get the values that was shown, I'll use the index 1 as well.
//DELETE
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
delete arr[1];
console.log("using delete",arr)
//SPLICE METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let firstElement = arr.splice(1,1)
console.log("using splice",arr)
console.log("the method splice return the element removed from array",firstElement )
//FILTER METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let copyArr = arr.filter((element, index)=>index !== 1)
console.log("extra: using filter (will return a array copy)",copyArr)
This question already has answers here:
Filter and delete filtered elements in an array
(10 answers)
Closed 3 years ago.
I am iterating over an array of strings using forEach(), and testing each element's length to determine wether it is even or odd. If the length of the string is even, it will be removed using splice().
My input and output are shown below, and as you can see even though (i think) my conditions are correct, in my return array, I still get an even, two character word - which should have been spliced out.
Code:
function filterOddLengthWords(words) {
words.forEach(function(element, index) {
if (element.length%2===0) {
words.splice(index, 1);
}
})
return words;
}
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output); // --> [ 'there', 'is', 'now' ]
I understand where the error is, but I just don't know how to compensate for it. I could possibly rewrite this by creating an empty array at the beginning of the function, and then testing each element against the inverse condition, using the push() method to add each positive to the empty array. However, that is more inefficient and I'm curious to see if my way is possible. Thanks for the answers in advance.
By splicing an array, you change the index, but forEach takes the elements in advance and the old indices.
Usually by using splice, the iteration is started from the end and if some item is remoce, the index remains for the items before.
You could filter the array.
function filterOddLengthWords(words) {
return words.filter(function(element) {
return element.length % 2;
});
}
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output);
The problem with splicing the array in the forEach() is that when you splice() on the array at index 1 which has the element it the element at index 2 is is moved to index 1.
So in the next iteration when the index is 2 in the callback the element at the index 2 of the array is the value now instead of the element is. As now is odd it is kept but the element is is completely skipped.
Using Array.prototype.filter will work here as it does not modify the original array but instead collects the valid results into a new array.
this.arol.filter(x=>x.length!==0
?(this.arol.splice(this.arol.indexOf(x),1))
:!true)
I was trying to change it many different ways, but it still does not delete all elements of the array, it always leaves 1 or 2 behind deleting most of them.... I think the problem is with the condition... We are checking if the length of array elements is not 0 (which are all strings)...
Don't try to splice while filtering - instead, return from the filter callback a truthy or falsey value, depending on whether you want to include the item being iterated over in the new array, and use the resulting array that gets returned from .filter:
this.arol = this.arol.filter(x => x.length !== 0);
^^^^^^^^^^^^
If you want to maintain same outer array reference and mutate original you can splice in a loop if you work from end to start so as not to affect indexing you haven't arrived at yet as you change the array length:
const arr = [[1],[],[2]]
arr.reduceRight((_,c,i) => c.length || !!arr.splice(i,1))
console.log(arr)
The problem is you are trying to splice at the same time you are using filter. Filter does not remove elements from your array, it creates a new array with the filtered data, as described here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
You can assign the result to the same array as suggested by CertainPerformance.
If Splice is removed from that code then it will not delete elements. this.arol.splice(this.arol.indexOf(x),1) here it will iterate through every element inside that array and x will be current iteration which will splice from the array as you have written splice method. Remove splice it will work fine.
This is the code I have - can you please tell me what is wrong? I would like to remove a specific word from the array using splice, in this case "tree".
var array = ['dog', 'man', 'tree']
array.splice(array.indexOf('tree'));
The second argument to splice is the number of items to delete.
array.splice(array.indexOf('tree'), 1);
otherwise all following elements are deleted.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Just filter it:
const withoutTree = array.filter(word => word !== 'tree')
You also have to provide an argument specifying how many items to delete. Otherwise, all elements from the specified start index will be removed.
array.splice(array.indexOf('tree'), 1);
Javascript splice method works with index to be deleted and item to be deleted.
In your case-
var newArray = array.splice(2,1);
console.log(newArray);// outputs ['dog','man']
Here 2 is the index of the element to be deleted which is 'tree' in your case and the second argument defines the number of element to be deleted.
Where can I find a List class for javascript with add(obj) remove(obj) and contains(obj)?
you can already use push instead of add and pop instead of remove.
How do I check if an array includes an object in JavaScript? contains an answer for how to do contains.
You could write some simple array extensions:
Array.prototype.add = function (obj) {
if (this && this.length)
this.push(obj);
};
[1, 2, 3].add(4);
... etc
Those aren't hard features to implement. I would simply create my own custom type that inherited from Array and added the two additional methods you'd like (since you can already use push to add items).
You can just use the native javascript's arrays
var arr = [];
arr.push(5); // add(obj)
arr.indexOf(5); // returns the index in the array or -1 if not found -> contains(obj)
For removing, you can use arr.pop() to remove last element or arr.shift() to remove the first element.
More on javascript's arrays - http://www.hunlock.com/blogs/Mastering_Javascript_Arrays