Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 just 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading