Why does one item remain in the comments and how to fix it?

var ids = [200, 201]; var comments = [{ id: 201 }, { id: 200 }]; comments.forEach(function(comment, index) { if (ids.includes(comment.id)) { comments.splice(index, 1); } }); console.log(comments); // not empty 

    1 answer 1

    Care must be taken when using the splice function inside a loop. A frequent problem is holes in the case when elements are deleted in a row. Because of the change in the counter, the second element for deletion is simply skipped.

    To filter an array, use the filter function.

     comments = comments.filter(function(comment){ return !ids.includes(comment.id); }) 

    If you want to use splice, then instead of forEach , in which there is no control over the changes in the index, it is better to use the usual for

     for(var i=0;i<comments.length;){ var comment = comments[i]; if (ids.includes(comment.id)) { comments.splice(i, 1); }else{ i += 1; } } 

    Since when deleting an element from the middle, the indices after the removed one are shifted, increasing the counter is necessary only for the case when there was no deletion, this will prevent the second element from skipping satisfying the condition.

    You can remove the else branch and bring the loop into a more familiar form by checking the elements of the array from the end:

     for(var i=comments.length-1;i>=0;i--){ var comment = comments[i]; if (ids.includes(comment.id)) { comments.splice(i, 1); } }