bigpotato
bigpotato

Reputation: 27497

Why is my JS/jQuery loop stopping after 2 loops?

So I have an array with a lot of repeat values. myArr = ['yeh','yeh','yeh','hey']. I have an HTML form that allows the user to type in a word and if that word is in the array it'll delete all the repeat values and print out the new myArr without those values. However, my loop keeps stopping after a few loops without finishing deleting the rest of the duplicates. like if I had ['yeh','yeh','yeh'] and typed "yeh" in the form, it only deletes two of the 'yeh'.

HTML

<form id="remove_user" action="#" method="post">
        <label for="user_num">Remove user:</label>
        <input type="text" id="user_num" name="user_num" placeholder="number">
        <input type="submit" value="(-) remove">
    </form><!-- #remove_user -->

    <ul id="user_list"></ul><!-- #user_list -->

JS:

$('#remove_user').submit(function(){
    id = $('#user_num').val();
    $.each(myArr, function(i, value){
        if (value == id){
            myArr.splice(i, 1);
            console.log(myArr);
        }
    });
    console.log(myArr);
    $('#user_list').html('');
    for (var i=0; i < myArr.length; i += 1) {
        console.log(myArr[i]);
        $('#user_list').append('<li>' +myArr[i]+ '</li>');
    };
    return false;
});

UPDATED ANSWER (so as said below, I was modifying it while looping over it, so things were getting skipped. Instead of what I did before, I used grep to create a new array of all the values that didn't match the submitted value, then just went through diffValues elements one by one and printed each out):

$('#remove_user').submit(function(){
    id = $('#user_num').val();
    var diffValues = $.grep(myArr, function(value, i){
        return value != id;
    });
    console.log(diffValues);
    $('#user_list').html('');
    for (var i=0; i < diffValues.length; i += 1) {
        console.log(diffValues[i]);
        $('#user_list').append('<li>' +diffValues[i]+ '</li>');
    };
    return false;
});

Upvotes: 0

Views: 100

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39522

If you want to delete values in an array that you're actively looping with, you have to go through it backwards (as making the length of the array shorter that way wouldn't invalidate your loop).

id = $('#user_num').val();
for (var i = myArr.length - 1; i >= 0; i--) {
    if (myArr[i] == id) {
        myArr.splice(i, 1);
    }
}

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

When you splice the array, you are changing that array. So basically your array is going through these steps:

['yeh','yeh','yeh','hey']
  ^^^
splice, move iterator forward
['yeh','yeh','hey']
        ^^^
splice, move iterator forward
['yeh','hey']
              ^^^
end loop - one of the 'yeh' is still there

You might be interested in .grep().

Upvotes: 1

Related Questions