Let's say I have a list of elements a = document.getElementsByTag('li'). I want to delete every element in that list except for those at positions keep = [3, 5, 8]. Ordinarily, this could easily be done with a for loop, and just making sure to skip the good positions.
for (i = 0; i < a.length; i++) {
if (!keep.includes(i)) {
a[i].remove();
}
}
Unfortunately, when removing elements from a, that dynamically changes a, and the positions/indexes of everything get shifted. If I wanted to, it's not too hard to account for this shifting. But is there a a more straight-forward / elegant method to do this task? I'd like to learn a more proper method before I just hack things to make it work.
For the record, the new solution I was thinking of was something like
shift = 0;
len = a.length;
for (i = 0; i < len; i++) {
if (!keep.includes(i)) {
a[i-shift].remove();
shift++;
}
}