Removing Items From Array

Hello,

I am at a loss as to how my function can work, except for the number β€˜-45’.
Please can someone explain why? :sweat_smile:

Kindest regards.

const myArr = [-10, 20, -21, 10, -23, -45, -44, 13, 5, -1, 15, 1, -25, -45, 17, 16];

const removeNeg = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < 0) {
      arr.splice(i, 1);
    }
  }
  
  return arr;
}

console.log(removeNeg(myArr));

The issue has nothing to do with the number -45. You are changing the loop on which you are doing math, while you are doing that math.

Consider this:

const myArr = [-1, -2, -3, -4, -5, -6];

const removeNeg = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    console.log('\ni', i)
    console.log('arr[i]', arr[i])
    console.log('arr.length', arr.length)
    if (arr[i] < 0) {
      arr.splice(i, 1);
    }
  }
  
  return arr;
}

console.log(removeNeg(myArr));

Examine the output closely and it may make it clear what the issue is.

Ah, of course. By removing the element from the array I am skipping over the next element when incrementing β€˜i’.

It was just by chance that β€˜-45’ was the only number to suffer the consequences multiple times.

Much appreciated :+1:

1 Like

Right. Something to consider is that there is a way to avoid this. Hint: Does the problem exist if we do it backwards? And you could also fix what you were doing with a tiny bit of math, but that gets a little messy code, imho.

And what Randy says is true - in fact that is a better approach because manipulating arrays is costly, having to shift all those elements each time - Randy’s approach would avoid that by just creating a new array. But it’s good to understand what is happening with the approach you were trying.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.