javascriptintermediate15 minutes

Build a To-Do List with JavaScript Using Objects and Arrays

Create a simple interactive to-do list mini-project where users can add, remove, and mark tasks as completed. This challenge focuses on manipulating arrays of objects and implementing multi-step logic to manage a list of tasks.

Challenge prompt

Write a function named manageTodoList that accepts two parameters: the current array of to-do items (each an object with properties id, task, and completed) and an action object describing what to do. The action object will have a type (add, remove, toggle) and relevant data for that action. Your function should return a new updated array of to-dos based on the action performed. For 'add', add a new task with a unique id and completed = false. For 'remove', remove the task by id. For 'toggle', toggle the completed status of the specified task id.

Guidance

  • Use array methods like map, filter, and concat to produce new arrays instead of mutating the original.
  • Generate unique ids for new tasks by incrementing from the highest existing id or using a timestamp.
  • Use switch or if-else statements to handle different action types clearly.

Hints

  • Remember not to mutate the original tasks array directly; always return a new array.
  • For toggling task completion, map over the array and update the matching task by id.
  • When adding, create a new task object with the given task string and completed set to false.

Starter code

function manageTodoList(todos, action) {
  switch (action.type) {
    case 'add':
      // Your code here
      break;
    case 'remove':
      // Your code here
      break;
    case 'toggle':
      // Your code here
      break;
    default:
      return todos;
  }
}

Expected output

manageTodoList([{id: 1, task: 'Learn JS', completed: false}], {type: 'add', task: 'Write code'}) // Returns: [ // {id: 1, task: 'Learn JS', completed: false}, // {id: 2, task: 'Write code', completed: false} // ]

Core concepts

arraysobjectsimmutabilitycontrol flow

Challenge a Friend

Send this duel to someone else and see if they can solve it.