I am making a simple to do app and am stuck on updating the data array when a new task is added. Right now, if you add a new task, the entire array re-populates on the display and duplicate values are listed. How do I resolve this so that only one iteration of the array displays any time it is updated on the page?
const completedDivs = document.getElementById("completed");
const taskDivs = document.getElementById("tasks");
const addBtn = document.querySelector(".fa-plus");
const input = document.getElementById("newTask");
// SET UP DEFAULT TO DO TASKS
let todos = [
{ completed: false, task: "Make Coffee", id: 1 },
{ completed: false, task: "Walk the dog", id: 2 },
{ completed: true, task: "Make calculator app", id: 3 },
];
// SET UP REQUIRED VARIABLES
let taskNo = (completedDivsLength + taskDivsLength) + 1;
// MAP OUT DEFAULT TASKS TO DISPLAY
function generateToDo() {
todos.map(todo => {
// CREATE A NEW DIV
let newTask = document.createElement("div");
// GIVE THE DIV AN ID
newTask.id = `div${taskNo}`;
if(todo.completed) {
// FORMAT THE DIV
newTask.innerHTML = `<input type="checkbox" id="task${taskNo}" checked>
<label for="task${taskNo}">${todo.task}</label>
<i class="far fa-trash-alt" id="trash${taskNo}"></i>`
// Check the item off the list
newTask.classList.add("checked");
// Add the task to the completed list
completedDivs.appendChild(newTask);
} else if (!todo.completed) {
// FORMAT THE DIV
newTask.innerHTML = `<input type="checkbox" id="task${taskNo}">
<label for="task${taskNo}">${todo.task}</label>
<i class="far fa-trash-alt" id="trash${taskNo}"></i>`
// Uncheck the task from the list
newTask.classList.remove("checked");
// Move the task to the To Do list
taskDivs.appendChild(newTask);
}
// INCREMENT THE TASK NO BY 1
taskNo++;
});
}
// ADD NEW TASKS
addBtn.addEventListener("click", () => {
todos.push({ completed: false, task: `${input.value}`, id: taskNo });
generateToDo();
// RESET THE INPUT FIELD TO NOTHING
input.value = "";
});
// AUTOMATICALLY LOAD THE DEFAULT TO DOS
window.onload = generateToDo();
question from:
https://stackoverflow.com/questions/65928603/displaying-array-on-page-getting-duplicated-results-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…