0

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.

2
  • 1
    What is your question? Commented Mar 30, 2018 at 22:07
  • You are iterating through an array and in between deleting an item of it, which will rearrange the index and this will change the behavior of loop in the following iteration. Commented Mar 30, 2018 at 22:18

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

Comments

0

I believe you are asking why you are not getting the results you want from that example. The reason behind this is that you are altering the length of array a in your loop while expecting the indices to not change.

So by the time you reach ind = 2, you are trying to remove items from an index that doesn't exist. To fix this you would need to keep a count of how many items you have removed and change console.log(a.splice(ind, 1)); to be console.log(a.splice(ind - itemCount, 1));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.