jack blank
jack blank

Reputation: 5195

trying to remove only string element from an array but cant loop right

hi im trying to remove only the string element from an array. I want to make a loop that checks to see if the el is a string and if it is a string it must be spliced. but right now it only removes the 1st matching element that's a string. why?

   var arr = [1,2, 'a', 'b']
    for(var i = 0; i < arr.length; i++)
        if(typeof arr[i] === "string"){
            var index = arr.indexOf(arr[i]);
                if(index > -1){
                    arr.splice(index, 1)

                }
                console.log(arr);
        }

Upvotes: 0

Views: 48

Answers (4)

Elliveny
Elliveny

Reputation: 2203

The arr.length changes when you remove an item, pushing your index 1 character ahead of where you expect to be, so you need to compensate for it. Add...

i--;

after the splice. Like this:

   var arr = [1,2, 'a', 'b']
    for(var i = 0; i < arr.length; i++)
        if(typeof arr[i] === "string"){
            var index = arr.indexOf(arr[i]);
                if(index > -1){
                    arr.splice(index, 1)
                    i--;                    
                }
                console.log(arr);
        }

Upvotes: 1

Scimonster
Scimonster

Reputation: 33409

Your modifying the array in place. Let's look at your iterations.

(i=0, type number)
[1,2,'a','b']

(i=1, type number)
[1,2,'a','b']

(i=2, type string)
[1,2,'b'] // removed 'a' at index 2

(i=3, type string)
[1,2,'b'] // there is no 4th item

I recommend just using filter() to filter the array:

arr=arr.filter(function(item){return typeof item != 'string'})

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You're modifying the array which you're looping. So you're modifying it in run time, so that's affecting your results. You shouldn't splice an array while you're iterating through it.

You can just do the below using Array.filter

arr = arr.filter(Number);

Upvotes: 2

CD..
CD..

Reputation: 74146

You can filter the array like:

arr.filter(function(item){ return typeof item !== 'string';});

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Upvotes: 1

Related Questions