Search code examples
javascriptarraysobjectforeachjavascript-objects

Is there any alternative to Array.forEach as I am not able to perform an action for every element inside an array


I am a newbie JavaScript developer. I am creating a ToDo list, and I am stuck in between.

I have created a function to delete all the completed tasks.

Below there's an array tasks containing various objects that contain information about the tasks.

What I want is if the object contains completion === true, then the same object should be removed from the array tasks. And I want this to be done for every single completed task.

But the problem is that the Array.forEach is removing only the first completed task. The rest completed tasks are as it is.

Thanks in advance if anyone can help me and tell me why is that happening...

Here's the code.

    const allCompletedTasksOnPage = document.querySelectorAll(".completed");
    let confirmDelete;
    if (allCompletedTasksOnPage.length > 0) {
        confirmDelete = confirm(`Are you sure, you want to delete all ${allCompletedTasksOnPage.length} completed tasks?`);
    };
    if (confirmDelete) {
        tasks.forEach((task) => {
            if (task.completion === true) {
                tasks.splice(tasks.indexOf(task), 1);
            };
        });
        allCompletedTasksOnPage.forEach((task) => {
            task.remove();
        });
    };
});```

Solution

  • Use while instead foreach because when an item is removed you have to check the same index again.

    if (confirmDelete) {
            var index=0;
            while(index<tasks.length) {
                let task=tasks[index];
                if (task.completion === true) {
                    tasks.splice(index, 1);
                    index--;
                };
                index++;
            };
           
        };