0

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);
        }

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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);
        }

1 Comment

The arr.filter option is much better, but hopefully this helps you understand why your code wasn't working
0

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'})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.