Making a todo app, but got stucked at deleting specific value in array, what am i doing wrong and how should i correct it? splice acts same as shift method.
Also is there any other way or data structure that can be used for todo app.
const form = document.querySelector("form");
const todoInput = document.querySelector(".todoInput");
const list = document.querySelector(".renderListHere");
const todoList = [];
form.addEventListener("submit", (event) => {
event.preventDefault();
const text = todoInput.value.trim();
if (text === "") {
console.log("enter something");
} else {
addTodo(text);
todoInput.value = "";
}
});
const addTodo = (text) => {
const todo = {
id: Date.now(),
text,
};
todoList.push(todo);
renderTodo(todo);
};
const renderTodo = ({ text, id }) => {
const li = document.createElement("li");
li.classList.add("todoListItems");
li.innerHTML = `
<span> ${text} </span>
<button id="${id}" class="del-btn"> x
</button>
`;
list.append(li);
};
list.addEventListener("click", (event) => {
if ((event.target.className = "del-btn")) {
const arr = todoList.filter(
(item) => item.id === parseInt(event.target.id)
);
todoList.splice(arr, 1);
}
});
I think you misunderstood the filter
method.
The Array.filter()
function returns a new array, so in your case, you could use:
todoList = todoList.filter(
(item) => item.id !== parseInt(event.target.id)
);
So you are filtering todoList
with only the items with id different than event.target.id
, and applying the result to the same todoList
variable.