0

Here is an Array of DOM elements, and I want to remove all those elements that have a certain class, in this case "checked-item". also I want to mutate the original array so I think filter method is out of the question.

taskArr = [some DOM Elements]
taskArr.forEach(function (task) {
 if (task.children[1].className.includes("checked-Item")) {
   taskArr.splice(taskArr.indexOf(task), 1);    
}
});
6
  • 1
    Why do you need to mutate the original array? Commented May 20, 2021 at 6:48
  • Your code looks like it should work. What doesn't work in it? Commented May 20, 2021 at 6:49
  • It removes some elements but not all. I don't know why @zhokya Commented May 20, 2021 at 6:51
  • @Usman-FE Can you provide a minimal reproducible example? It seems to work fine for me. Commented May 20, 2021 at 7:09
  • 1
    @Ivar add the class to consecutive elements and it won't work. splice will break the for loop. Commented May 20, 2021 at 7:11

2 Answers 2

0

Your error is probably because you splice elements inside loop, so if you console log the task, not every will be in output. I found an solution, without foreach:

taskArr = [some DOM Elements]
const length = taskArr.length;
var deleted = 0;
for(var i = 0; i < length; i ++){
     if(taskArr[i - deleted].children[1].className.includes("checked-Item")){
         taskArr.splice(i - deleted, 1);
          deleted ++;
     }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or you can loop from length to 0 in the reverse direction. You don't have to keep track of deleted in that case: Looping through array and removing items, without breaking for loop
0

When a list is mutated while iterating, there can be side effects. The splice can cause the subsequent item to be skipped. This is one reason immutable functions like filter are much easier to reason about.

4 Comments

Is there any way I can mutate the original Array using filter method?
@Usman-FE Assign the outcome back to the original array?
Generally after filter I would use map in order to modify the matched items.
I should add that if the subset of filtered items were not needed after processing, the filter could be followed with a forEach.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.