CodeBlanks Logo Icon CodeBlanks

Completing and deleting tasks

JavaScript course · Beginner · Lesson 103/133

Find a task with findIndex to complete it and remove it with filter.

Finding a position with findIndex

To find a task's position in the array we use the findIndex method. It takes a predicate function and returns the index of the first element that matches it.

The call tasks.findIndex(function (task) { return task.id === id; }) gives the position of the task whose id matches. If nothing matches it returns -1, so you should check for -1 before using the result.

Deleting with filter

A safe way to remove a task is the filter method. filter builds a new array from the elements that match a condition and leaves the original untouched. To delete, you flip the condition.

When you write tasks = tasks.filter(function (task) { return task.id !== id; }), the ones whose id does not match stay and the matching one is gone. Reassigning the result to tasks updates the list.

Mutation and new array

There are two ways to change an array: in-place mutation or returning a new array. push mutates the array in place; filter returns a new array.

So you must assign the result of filter to a variable, otherwise the change is lost. push needs no such assignment. Using both correctly reduces bugs.

Exercise Complete and delete a task

Define two functions named completeTask and deleteTask. completeTask should find the task with findIndex and set its completed to true; if not found, do nothing. deleteTask should keep the tasks whose id does not match with filter and reassign the result to tasks.

Show example solution
completeTask finds the position with findIndex and sets completed to true. deleteTask keeps the tasks whose id does not match using filter.

Example solution:
function completeTask(id) {
  const index = tasks.findIndex(function (task) {
    return task.id === id;
  });
  if (index !== -1) {
    tasks[index].completed = true;
  }
}

function deleteTask(id) {
  tasks = tasks.filter(function (task) {
    return task.id !== id;
  });
}

Test yourself

  1. What does findIndex return when no match is found?

    • undefined
    • null
    • 0
    • -1
    Show answer

    -1 — findIndex returns -1 when no element matches the condition, so you should check the result.

  2. Complete the filter condition

    function deleteTask(id) {
      tasks = tasks.filter(function (task) {
        return task.id !== ____;
      });
    }
    Show answer
    function deleteTask(id) {
      tasks = tasks.filter(function (task) {
        return task.id !== id;
      });
    }
  3. Match methods to their behavior

    findIndex
    Returns position
    filter
    Returns new array
    push
    Mutates in place

All lessons in Beginner