Search code examples
javascriptarrayssortingtypeof

Deleting everything that is not a number from the array. Why isn't this working?


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?


Solution

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