Home > Enterprise >  Removing all but a few specific elements from a list in javascript?
Removing all but a few specific elements from a list in javascript?

Time:09-12

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  ;
  }
}

CodePudding user response:

I think you can use filter instead of looping. I find it quite idiomatic in javascript:

a = a.filter(x => keep.includes(x))

CodePudding user response:

If you want to maintain the indexing of the keep values in an array then instead of removing the other values, You can replace them with undefined.

Here you go :

const a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const keep = [3, 5, 8];

a.forEach((num, index) => {
  if (!keep.includes(index)) {
    a[index] = undefined
  }
});

console.log(a);

  • Related