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;
});
When you
splicethe array, you are changing that array. So basically your array is going through these steps:You might be interested in
.grep().