Learn JavaScript · lesson 28 of 60 · about 9 minutes
Project: Sam's To-Do List
Run Sam's to-do list for the site: process commands that add and finish tasks, remove items with splice, and ignore task numbers that don't exist.
What you'll learn
- Store tasks in an array
- Process a list of commands
- Remove items with splice()
Sam's to-do list
Sam keeps a to-do list for the site in an admin box. Each command Sam typed is a string in the array todo, like add Fix the footer or done 1. The page runs them in order on an empty tasks array and shows what's left to do. Task numbers start at 1 but indexes start at 0, and a number that isn't a task has to be ignored.
How it works
Commands arrive as strings like "add Buy milk". For each one:
add <task>: push the taskdone <number>: remove that task withsplice(index, 1)show: print the numbered list
splice(i, 1) removes one item at position i and returns it in an array.
The to-do list
const tasks = [];
const commands = ["add Feed Phoebe", "add Finish lesson", "add Stretch", "done 2", "show"];
for (const cmd of commands) {
const [action, ...rest] = cmd.split(" ");
const text = rest.join(" ");
if (action === "add") {
tasks.push(text);
} else if (action === "done") {
const [removed] = tasks.splice(Number(text) - 1, 1);
console.log(`Completed: ${removed}`);
} else if (action === "show") {
tasks.forEach((t, i) => console.log(`${i + 1}. ${t}`));
}
}Output
Completed: Finish lesson
1. Feed Phoebe
2. StretchTip
Users count from 1 but arrays count from 0, so subtract 1 when turning a task number into an index.
Tip
splice with a negative position counts from the end, so splice(-1, 1) removes the last item. That's why done 0 has to be caught before it reaches splice.
Now try it yourself
This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.