0

As an absolute javascript beginner, I am currently practicing on a todo app. The entries should be sorted by title, date, status and priority by clicking on the column header. Attached is my attempt, however I seem to be doing something wrong. Can anyone help me with this?

const todos = [
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 1", description: "first try", prio: 1, state: "done"}
];

const titleSort = document.getElementById("sort-title");

function sortTitle(a, b) {
  // alert("Titel sortieren");

  const titleA = a.title.toUpperCase();
  const titleB = b.title.toUpperCase();

  let comparison = 0;
  if (titleA > titleB) {
    comparison = 1;
  } else if (titleA < titleB) {
    comparison = -1;
  }
  return comparison;
}

titleSort.addEventListener("click", sortTitle);
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Colette
  • 23
  • 3

1 Answers1

2

The event listener will pass the event object to your sortTitle function... Not the todos array. Then, your return will end nowhere.

So... To the event listener, you have to pass a function to be executed. In that function, you specify what array to sort and where to return it.

const todos = [
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 2", description: "second try", prio: 1, state: "done"},
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 3", description: "third try", prio: 1, state: "done"},
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 1", description: "first try", prio: 1, state: "done"}
];

const titleSort = document.getElementById("sort-title");

function sortTitle(array) {
  
  return array.sort((a,b) => {

    const titleA = a.title.toUpperCase();
    const titleB = b.title.toUpperCase();

    let comparison = 0;
    if (titleA > titleB) {
      comparison = 1;
    } else if (titleA < titleB) {
      comparison = -1;
    }
    return comparison;
  })
}

// I don't know where you want to return the sorted array... So I just console logged it.
titleSort.addEventListener("click", () => console.log(sortTitle(todos)));
.as-console-wrapper{
  max-height: 100% !important;
}
<button id='sort-title'>Sort me</button>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • This works wonderfully and your solution has helped me a lot! Now the sorted array should be returned to the list. This I have created with template strings:
    ${todo.title}
    . What is the best way to do this?
    – Colette Jun 03 '23 at 19:55
  • There certainly is existing documentation about your templating system. – Louys Patrice Bessette Jun 03 '23 at 20:47