0

I'm working on a todo list assignment that basically consists of a user being able to create a List and within that List he would be able to create Todo items. I was working on the function to delete a todo from a given list. Now I was able to get this to work by iterating through each list, find a matching Id of the Todo item the user wants to delete, get the index of that item and use the Splice() method to remove it from the original array, all this is fine and works great but my concern is that the initial ForEach iteration will continue iterating each list even if the ID was found so my question is how do I break from the iteration once a matching ID is found? Perhaps I'm using the wrong approach to accomplish, sorry for making your eyes bleed in advance :)

const lists = JSON.parse(localStorage.getItem('lists')) || [];

generatedTrashIcon.addEventListener('click', (event) => {
  deleteTodo(generatedTrashIcon.previousSibling.id);
});

const deleteTodo = (deletedTodoId) => {
  lists.forEach((list) => {
    const findTodo = list.todos.find((todoItem) => todoItem.id === deletedTodoId);

    if (findTodo) {
      const todoIndex = list.todos.indexOf(findTodo);

      list.todos.splice(todoIndex, 1);
      localStorage.setItem('lists', JSON.stringify(lists));
      appendTodosToView(clickedListId);
    }
  });
};

here's how the output of the lists object is structured :

{
    "id": "1622610431641",
    "name": "Productivity",
    "todos": [
        {
            "id": "1623013270585",
            "todoItem": "code all day!"
        }
    ]
}
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
  • 2
    `forEach` is probably the wrong loop type then. You could just use a `find` in the outer loop and return `true` when `found` and `false` otherwise. – Nick Jun 06 '21 at 21:26
  • 1
    There's a `findIndex` method also... – Heretic Monkey Jun 06 '21 at 21:30
  • Thanks @Nick, initially that's where I was headed, however the todoItems are stored as an array of objects within the List.todos property which is why I used the forEach method first to loop through each list.todos and find a matching todoID. I could potentially use the find method to first find the list id but was wonder if with the solution above there was a more optimized solution to break out of the forEach loop – Serge Sroujian Jun 06 '21 at 21:38

0 Answers0