Looping Through Array and Removing Items, Without Breaking For Loop

Looping through array and removing items, without breaking for loop

The array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed, and your cached .length is obsolete.

To fix it, you'd either need to decrement i after a .splice(), or simply iterate in reverse...

var i = Auction.auctions.length
while (i--) {
...
if (...) {
Auction.auctions.splice(i, 1);
}
}

This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.

How to iterate over an array and remove elements in JavaScript

Start from the top!

var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = elements.length -1; i >= 0 ; i--){
if(elements[i] == 5){
elements.splice(i, 1);
}
}

Remove array item using for...of loop

You can't reasonably use for-of for this. If you remove the "current" entry during the iteration, you'll skip the next entry, because of the way array iterators are specified (they use the index of the entry). You can see that with this contrived example:

const array = [1, 2, 3];

for (const entry of array) {

console.log(entry);

if (entry === 2) {

array.splice(1, 1);

}

}

console.log(array);

How to remove items from a list while iterating?

You can use a list comprehension to create a new list containing only the elements you don't want to remove:

somelist = [x for x in somelist if not determine(x)]

Or, by assigning to the slice somelist[:], you can mutate the existing list to contain only the items you want:

somelist[:] = [x for x in somelist if not determine(x)]

This approach could be useful if there are other references to somelist that need to reflect the changes.

Instead of a comprehension, you could also use itertools. In Python 2:

from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)

Or in Python 3:

from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)

Loop through array when removing elements

I find simpler to iterate in the other direction :

for (var i=myarray.length; i--; ) {
if (myarray[i] === 'something') myarray.splice(i, 1);
}

This way you don't have to change the increment when removing.

Many developers, especially the ones who didn't deal with C-like languages before JavaScript, find it confusing to deal with the subtleties of the decrement operator. The loop I wrote can also be written as

for (var i=myarray.length-1; i>=0; i--) {

Looping through an array of arrays and removing an item

Issue is with splice(i, 1), This should be splice(2, 1) since you need to remove the 2 (indexed) item.

const Data = [["Name", "Area", "Position", "Shift",]];
const otherData = [["Training A","Course A","Level","Curricula"],["Training B","Course B","Level","Curricula"],["Training C","Course C","Level","Curricula"]];
var CombinedData = otherData.map(x=>[...Data[0], ...x]);

for(let i = CombinedData.length -1; i>=0; i--){
if(CombinedData[i][2] == Data[0][2]){
CombinedData[i].splice(2,1);

}
}
console.log(CombinedData);

Is it supposed to be safe to remove elements from an array while iterating with for..of in JavaScript?

No, (as your example demonstrates) it's not safe to remove elements from an array while iterating it.

The default array iterator stores the current index, and it does not update this index when you call splice on the array. It just continues at the same position, no matter what you did to the elements in the array. You can read the spec for ArrayIterator objects, they basically work like a for (var index=0; index<array.length; index++) yield array[index]; loop.

Looping through array and removing smallest number

A straightforward approach ...

const array = Array
.from(
{ length: 50 },
() => parseInt(Math.random() * 100 + 1),
)
.sort((a, b) => a - b);

// mutate/shorten `array`, remove all values equal to the minimum value.
array.splice(0, array.lastIndexOf(array[0]) + 1);

Proof of the above implementation ...

const array = Array
.from(
{ length: 50 },
() => parseInt(Math.random() * 100 + 1),
)
.sort((a, b) => a - b);

console.log({
arrayLength: array.length,
minValue: array[0],
sorted: array,
});

// mutate/shorten `array`, remove all values equal to the minimum value.
array.splice(0, array.lastIndexOf(array[0]) + 1);

console.log({
arrayLength: array.length,
shortened: array,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

How to remove multiple specific elements from an Array using a loop in JavaScript?

Your error is probably because you splice elements inside loop, so if you console log the task, not every will be in output.
I found an solution, without foreach:

taskArr = [some DOM Elements]
const length = taskArr.length;
var deleted = 0;
for(var i = 0; i < length; i ++){
if(taskArr[i - deleted].children[1].className.includes("checked-Item")){
taskArr.splice(i - deleted, 1);
deleted ++;
}
}

How can I remove an item from an array while I use forEach on this array?

What you will want to do is loop over the array in reverse:

let i = tests.length
while(i--) tests[i].testme()

Here it is in action:

//creating a test array

var tests = [];

tests.push(new Test(1));

tests.push(new Test(2));

tests.push(new Test(3));

tests.push(new Test(4));

function Test(n) {

this.n = n;

this.testme = function() {

if(this.n < 3) {

tests.splice(tests.indexOf(this), 1); //remove me from the array tests please!

console.log(this.n, "I got removed!");

} else {

console.log(this.n, "I can stay!");

}

}

}

console.log("tests length: ", tests.length);

let i = tests.length

while(i--) tests[i].testme()

console.log("tests length: ", tests.length); //output should now be 2


Related Topics



Leave a reply



Submit