Removing elements in a "for, of" loop
1 September 2018
Yes, you can remove an element from an array while you’re iterating over it in a for/of
loop in Javascript. But you probably don’t want to.
A better solution, if you can replace the array, might be to not use a loop at all. Use the Array.filter
to get a new array, which only includes the elements you need:
clients = clients.filter((client)=>!client.disconnected);
Here’s what other options are available:
/*
* Sure it works, but it's easy to mess up by forgetting to increment and
* leaves a variable in the outside scope
*/
let i =0;
for (let client of clients) {
i++;
if (client.disconnected) {
clients.splice(i, 1);
}
}
/*
* Don't ever do this! Results in O(N^2) complexity which means it's very
* slow, and quickly gets slower with array size
*/
for (let client of clients) {
if (client.disconnected) {
clients.splice(clients.indexOf(client), 1);
}
}
/*
* Also works, but it's easy to accidentally the decrement
*/
for (let i = 0; i < clients.length, i++) {
let client = clients[i];
if (client.disconnected) {
client.splice(i, 1);
i--;
}
}
/*
* Your best option if you have to delete in place
*/
for (let i = clients.length; i >= 0, i--) {
let client = clients[i];
if (client.disconnected) {
client.splice(i, 1);
}
}