0

So i'm trying to write a function that deletes all the strings from array.

It works, but deletes only half of them, why?

let list = [1,2,'a','b', 'c', 'd', 'e'];


function filter_list(l) {
    for (let i = 0; i < l.length; i++) {
        if(typeof l[i] === 'string') {
            l.splice(l.indexOf(l[i]), 1);
        }
    }
    console.log(l)
}

filter_list(list)
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
gunniq
  • 21
  • 5
  • Use `filter` based on the `typeof` the value. – gorak Feb 04 '21 at 14:57
  • using your `split` method, your index `i` becomes desynced from the index you're trying to access because you're deleting stuff while you're iterating over the same stuff. So for example if `i` is 3, and you're checking if you should delete the 4th element, and you DO delete it, then the next element moves down to index 3, but your next iteration starts at 4 and you've skipped one. The way to deal with this is to iterate backwards – TKoL Feb 04 '21 at 14:59
  • Although really the ideal way to do it is `array.filter()`, as in the answer below. – TKoL Feb 04 '21 at 15:00

2 Answers2

2

Use Array.prototype.filter() to return a filtered subset Array, and typeof to check the operand type:

const list = [1,2,'a','b', 'c', 'd', 'e'];
const nums = list.filter(x => typeof x !== "string"); 
console.log(nums)
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

const list = [1,2,'a','b', 'c', 'd', 'e'];
const nums = list.filter(i => typeof i !== "string"); 
console.log(nums)

This checks each element and excludes those of type string.

Andy
  • 648
  • 8
  • 21