-1
let arr = [1, "5", 3, 27, undefined, { name: 'Steven' }, 11];

for (let i = 0; i < arr.length; i++) {
    if (typeof arr[i] !== 'number') {
        arr.splice(i, 1);
    }
}
console.log(arr); // output is: [1, 3, 27, {…}, 11]

If I swap the places of the object and the last number output is different.

let arr = [1, "5", 3, 27, undefined, 11, { name: 'Steven' }];

for (let i = 0; i < arr.length; i++) {
    if (typeof arr[i] !== 'number') {
        arr.splice(i, 1);
    }
}
console.log(arr); // output is: [1, 3, 27, 11]

Can anyone explain why?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Protip: avoid `splice`, just use `filter`. – Dai Oct 07 '22 at 18:09
  • 1
    picture the array as a stack of books with the first index at the bottom. You slowly move up from book to book. You remove a book, all of the books above it shift down one location. You ignore the book that just moved down and move on to the next book. That is how your loop works. You do not look at the index again, you ignore it so if you have two invalid indexes in a row you skip the second one. – epascarello Oct 07 '22 at 18:19
  • Thanks a lot, perfectly explained, I overlooked that. – andrijadenic9 Oct 07 '22 at 18:25

1 Answers1

-1

You shouldn't mutate an arrays length while you are iterating over it. Would recommend you use filter

Kartik Rawat
  • 244
  • 2
  • 7