clusterBuddy
clusterBuddy

Reputation: 1554

Javascript array with for loop + condition removes unnecessary elements

I am looping through an array and for some reason the loop + condition + splice is removing indexes that shouldn't be removed and keeping others that should be removed, can someone point what's the error with my syntax?

arr2 = ['agg', 45, 'ghj', ' ', 9999, 12, 'aa', 'bb'];

function returnAlphanumeric(array){
    for (var i=0; i<array.length; i++){
        if (typeof array[i] !== "number"){
            array.splice(i, 1);
        }
    }
    console.log('Your new array is: '+array);
}
returnAlphanumeric(arr2);

Upvotes: 0

Views: 42

Answers (2)

erdysson
erdysson

Reputation: 1480

why don't you use filter method :

arr2 = ['agg', 45, 'ghj', ' ', 9999, 12, 'aa', 'bb'];
arr2.filter(a => typeof a === "number"); // 45, 9999, 12

Upvotes: 3

Ruhul
Ruhul

Reputation: 1030

Can you try this, you will have to decrement the counter as splice will make shifts in you array??

function returnAlphanumeric(array){
    for (var i=0; i<array.length; i++){
        if (typeof array[i] !== "number"){
            array.splice(i, 1);
            i--;
        }
    }
    console.log('Your new array is: '+array);
}

Upvotes: 3

Related Questions