I have the following for loop, and when I use splice()
to remove an item, I then get that 'seconds' is undefined. I could check if it's undefined, but I feel there's probably a more elegant way to do this. The desire is to simply delete an item and keep on going.
for (i = 0, len = Auction.auctions.length; i < len; i++) {
auction = Auction.auctions[i];
Auction.auctions[i]['seconds'] --;
if (auction.seconds < 0) {
Auction.auctions.splice(i, 1);
}
}
Try to relay an array into newArray when looping:
This is a pretty common issue. The solution is to loop backwards:
It doesn't matter if you're popping them off of the end because the indices will be preserved as you go backwards.
You can just look through and use
shift()
There are lot of wonderful answers on this thread already. However I wanted to share my experience when I tried to solve "remove nth element from array" in ES5 context.
JavaScript arrays have different methods to add/remove elements from start or end. These are:
Essentially none of the above methods can be used directly to remove nth element from the array.
This essentially leaves us with only one array method
Array.splice
to perform removal of nth element (there are other things you could do with these methods as well, but in the context of this question I am focusing on removal of elements):Here is the code copied from original answer (with comments):
Another noteworthy method is
Array.slice
. However the return type of this method is the removed elements. Also this doesn't modify original array. Modified code snippet as follows:Having said that, we can still use
Array.slice
to remove nth element in the following way and as you can observe it is lot more code (hence inefficient)Although your question is about deleting elements from the array being iterated upon and not about removing elements (in addition to some other processing) efficiently, I think one should reconsider it if in similar situation.
The algorithmic complexity of this approach is
O(n^2)
as splice function and the for loop both iterate over the array (splice function shifts all elements of array in the worst case). Instead you can just push the required elements to the new array and then just assign that array to the desired variable (which was just iterated upon).Since ES2015 we can use
Array.prototype.filter
to fit it all in one line: