If page reloaded, splice method returned [0]{‘C’} instead of 0:{‘B’}
todos = [0:{"title":"A"}, 1:{"title":"B"}, 2:{"title":"C"}] //store todos - localStorage
deletedTodo = [0,2] // remove A & C from todos - store removed element index - localStorage
window.addEventListener("load", (e) => {
todos = JSON.parse(localStorage.getItem("todos")) || [];
clearTodo();
});
function for checking deleted indexes that should removed from todos object then return updated todos object
otherwise return display Todos()
function clearTodo() {
if (
JSON.parse(localStorage.getItem("deletedTodo")) &&
JSON.parse(localStorage.getItem("deletedTodo")).length > 0
) {
for (
let index = 0;
index <= JSON.parse(localStorage.getItem("deletedTodo")).length;
index++
) {
todos.splice(JSON.parse(localStorage.getItem("deletedTodo"))[index], 1);
}
localStorage.setItem("todos", JSON.stringify(todos));
localStorage.setItem("deletedTodo", JSON.stringify([]));
deletedIndexex = [];
return displayTodos();
} else {
return displayTodos();
}
}
3
Answers
When you splice you should decrease your index by number of deleted items since the array got shorter. To behave your array normally load it from the local storage only once. And since you splice a different array, just filter it:
For example
Here’s the modified code: