...

/

Implementing the Sorting Functionality

Implementing the Sorting Functionality

Learn how to implement sorting in Svelte using a generic sorting algorithm.

We have our table ready and styled. In the next two lessons, we're going to take a look at how to implement the sorting and filtering functionalities with generic algorithms that we can reuse elsewhere and apply to other projects.


Create the sorting algorithm

Let's start with the actual sorting algorithm. Take a look at the following example where we only have the sorting algorithm and some example data:

Console
Inspect the sorting algorithm

This algorithm uses the built-in array.sortSort the elements of the array in place and returns a sorted array method. It expects a callback compare function that decides how to sort the array. It's important to mention that the sort method returns a reference to the original array, so if we mutate the sorted dataset, the original array will be mutated as well. This function works by accepting three different arguments:

  • array: The array of objects to be sorted.

  • key: The key being used for sorting inside the array (passed as a ...