Skip to content
Advertisement

for loop skipping one item in array in javascript

I am trying to make a function that removes strings from an array if they include a character in a certain other list

Here is the code:

var possible = ["salutations", "goodbye", "thanks", "welcome"];
var incorrect = ["o"];

console.log(possible);

function narrowdown(possible, incorrect)
{
    var templist = possible;
    for (i in possible)
    {   
        console.log(i + " " + possible[i]);
        var array1 = possible[i].split("");
        var common = array1.filter(value => incorrect.includes(value));
        console.log(common)
        if (common.length)
        {
            templist.splice(i, 1);
        }
    }
    possible = templist;
}

narrowdown(possible, incorrect);

console.log(possible);

Here I am trying to remove all the words that include the letter o. I created a temporary array in the function because it has happened to me before that a for loop skips items altogether. The code first logs the index of the item in the list and then the item itself.

Then it turns the word into an array and checks for overlap between it and the “incorrect” array. It does that correctly and logs the overlapping characters. The issue seems to be that it skips over the “goodbye” item for some reason. It doesn’t even process it.

Here is the output I am getting:

[ 'salutations', 'goodbye', 'thanks', 'welcome' ]
0 salutations
[ 'o' ]
1 thanks
[]
2 welcome
[ 'o' ]
[ 'goodbye', 'thanks' ]

Advertisement

Answer

First of all, for (i in possible) is a bad way of looping through an array since it retrieves the keys before the loop begins and it never updates that list of keys. Also, if someone assigns an attribute to the array, like possible.foo = 17, then your loop will also go through that. The issue you’re having is that when you splice the array, everything else is shifted one to the left, changing their indices to be one less, so your new index actually skips over the next element. The fix is to use a conventional for loop and decrement i after splicing:

for (let i = 0; i < possible.length; i ++) {
    // more code...
    if (common.length) {
        templist.splice(i, 1);
        i --;
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement