1

I would like to remove multiple items from an array by an array of indexes.

const indexes = [0, 1, 3];
const values = [0, 1, 2, 3, 4, 5];

indexes.forEach((idx) => {
  values.splice(idx, 1);
});

console.log(values);

When looping for the second time, the index is wrong because the array is shorter.

What should I do so the outcome would be [2, 4, 5]?

axtck
  • 3,707
  • 2
  • 10
  • 26

1 Answers1

4

You're removing items from the array while iterating over it, which is a problem because after the first element gets removed, all the elements that follow it are no longer at the same index that the indexes are pointing to. Filter the array instead:

const indexes = [0, 1, 3];
const values = [0, 1, 2, 3, 4, 5];

const filtered = values.filter((_, i) => !indexes.includes(i));
console.log(filtered);

If you must mutate the existing array, go backwards so that the highest indexes get removed first:

const indexes = [0, 1, 3];
const values = [0, 1, 2, 3, 4, 5];

for (const index of indexes.sort((a, b) => b - a)) {
  values.splice(index, 1);
}

console.log(values);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320