...

/

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:

JavaScript
const sort = (array, key, order) => {
const returnValue = order === 'desc' ? 1 : -1;
return array.sort((a, b) => a[key] > b[key] ? returnValue * -1 : returnValue);
};
const data = [
{ name: 'Nixon Wolf', score: 1933 },
{ name: 'Jan England', score: 505 },
{ name: 'Rowe Rowland', score: 1175 }
];
// Sorted by score
console.log(sort(data, 'score', 'asc'));
// Try to sort the same data by the "name" key

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 string). In the example above, we use the score property. We can then use this key using bracket notation. For ...