0

I have an array that is only supposed to contain 10 digit numbers. I am trying to eliminate entries in the array that contain a "-" symbol, but for some reason it is not working.

for(var z = 0; z<numArray.length; z++){
    if(numArray[z].includes("-")){
        numArray.splice(z, 0)
    }
}

is there something obvious that I am missing?

D. Fowler
  • 5
  • 2
  • ```numArray.splice(z, 1)``` will work – Gustavo Farias Jun 21 '21 at 16:07
  • 1
    The second argument to `splice` is the number of elements to remove at the index you've given in the first argument. `0` means "don't remove any," which is why nothing is being removed. Once you fix it, see the second issue in [the question marked by adiga](https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop). – T.J. Crowder Jun 21 '21 at 16:07
  • 1
    @placementw - Not *quite*, in the code above. You also have to deal with the index issue. – T.J. Crowder Jun 21 '21 at 16:07
  • Do not try to modify the length of an array you are iterating. – Tushar Shahi Jun 21 '21 at 16:08
  • @TusharShahi OP is wanting to remove elements... so.. ya kinda do need to change the length to remove elements – Samathingamajig Jun 21 '21 at 16:10
  • @T.J.Crowder you're right, just pointed what was wrong in this piece of code since the proper logic way to handle the situation had already been marked = ) – Gustavo Farias Jun 21 '21 at 16:11

2 Answers2

0

You can simply filter:

let withoutDashes = numArray.filter(val => !val.includes('-'));
Gershom Maes
  • 7,358
  • 2
  • 35
  • 55
0

It's a classic that when removing elements from an array, you either need to iterate through the array backwards or decrement the index variable, otherwise you could skip over elements that are right next to each other that both should be deleted.

Also, having 0 for the second argument means "replace 0", or in this case, "remove 0", so changing that to 1 will remove the elements

for(var z = 0; z<numArray.length; z++){
    if(numArray[z].includes("-")){
        numArray.splice(z, 1)
        z--;
    }
}
for(var z = numArray.length-1; z >= 0; z--){
    if(numArray[z].includes("-")){
        numArray.splice(z, 1);
    }
}

However, it's easier to just use Array.prototype.filter. This function returns a new array with only elements that evaluate to true based on the passed in function, so we only want to keep the ones that DO NOT INCLUDE "-"

numArray = numArray.filter((num) => !num.includes("-"));
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34