-2

i just confuse why splice in loop vs splice multi line have different result

example:

var list = ["0","1","2","3","4"];
var removeIndex = [0,2,4];  

case 1:

for (var i = removeIndex.length -1; i >= 0; i--)
list.splice(removeIndex[i],1);

result: list -> [1,3]

case 2:

list.splice(0,1);
list.splice(2,1);
list.splice(4,1);

result: list -> [1,2,4]

Does anyone know why?

#

i get it, that loop backwards case1 not shift index like case2 i f**king stupid that code case1 i copy from somewhere and i don't realize it(i alway think the loop is forwards).

  • 6
    your loop does it backwards. – Daniel A. White Aug 07 '18 at 12:45
  • 2
    The order of splice operations is different in both cases. The relation (spliced) index to value changes in your second case after each call, whereas it stays the same in the first one (at least as long as `removeIndex` is sorted that way). – Sirko Aug 07 '18 at 12:45
  • oh i get it, that backwards not shift index like case2. I f**king stupid that code case1 i copy from somewhere and i don't realize it(i alway think the loop is forwards). thank you very much and sorry for take your time. – Pongpon Khampun Aug 07 '18 at 13:46

1 Answers1

2

You loop backwards. It's better to use forEach anyways.

const list = ["0","1","2","3","4"];
const removeIndex = [0,2,4];  

removeIndex.forEach(item => list.splice(item,1))

console.log(list)

const list2 = ["0","1","2","3","4"];
list2.splice(0,1);
list2.splice(2,1);
list2.splice(4,1);

console.log(list2)
anttud
  • 736
  • 3
  • 9
  • oh i get it, that backwards not shift index like case2. I f**king stupid that code case1 i copy from somewhere and i don't realize it(i alway think the loop is forwards). thank you very much and sorry for take your time. – Pongpon Khampun Aug 07 '18 at 13:47