Search code examples
javascriptarraysforeachsplice

JavaScript array - splice call within forEach unexpected result


I noticed a bug within my code and tried to reproduce it with simpler JavaScript shown below. The goal is to sort an array and compare element 'x' to 'y' but not waste time comparing 'y' to 'x'. Note that I am also using objects comparing properties in my other code.

var a = [1, 3, 2, 5];
a.sort((b, c) => b - c);
a.slice().forEach((x, ind) => {
  console.log(a.splice(ind, 1));
  a.forEach(z => { console.log(z); });
});

The remaining elements of the above are 2 and 5. I would expect that elements 3 and 5 are removed. (Works the same with or without the copy using slice())

I ended up just reverting to for loops using indexes where the inner array's index starts at the outer array's index + 1.


Solution

  • Well, you start with

    [1, 2, 3, 5]
    

    and you remove the element at the 0 index, ending up with:

    [2, 3, 5]
    

    In your next iteration, you remove the element at the 1 index, ending up with

    [2, 5]
    

    In your next iteration, you remove the element at the 2 index, which doesn't exist, so you still have

    [2, 5]
    

    You probably want to do:

    console.log(a.splice(ind, 0));