FiltersLesson 155Free preview
Sort List
This lesson is part of How To · All levels
Summary
This lesson explains how to sort items in alphabetical or numerical order. JavaScript can take the entire item, sort it with a comparator, and then rearrange the elements in the DOM. Since the DOM does not automatically sort itself, node transfers are done with the appendChild after the data is sorted.
Key points
- Take the item as an array using a spread or Array.from before sorting
- Use localeCompare for text and numeric comparator for numbers
- The appendChild on an existing element will move it, not duplicate it
- Save the order direction so that the same button can reverse the ascending/descending sortir
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.