0

I have this code, and all I'm tryin' to do is delete values from the original arr array which are not numbers to output a revised array with number values only.

For some reason, it manages to weed out through certain values but not the others (check the console output below. The debugger didn't shed much light on this behaviour - could someone please help?

const arr = [3, 9, NaN, false, 13, -10, false, 17, 14, 9, 5, true, "error", true, false, "error", false];

for (let i = 0; i < arr.length; i++) {
  if (typeof arr[i] !== "number" || isNaN(arr[i]))
    arr.splice(i, 1);

}

console.log(arr);
  • If you have an array `[a, b, c, d, e]` and `i = 1` then you remove `b` and the array changes to `[a, c, d, e]` but you move `i` to `2` and thus evaluate `d` skipping over `c`. – VLAZ Nov 12 '21 at 21:41
  • `splice` changes the array length. [You can work backwards from the end of the array to the beginning](https://jsfiddle.net/z057cuqo/); – Andy Nov 12 '21 at 21:44
  • 1
    Thank you, both! – chessplayer Nov 12 '21 at 21:44

0 Answers0