Sorting a list or array has many uses in web applications, from lists to tables, it is very useful. Let's look at some of the ways data can be sorted in JavaScript
For sorting data in javascript, we make use of the sort() function and its parameters.
Sorting an Array of Strings
The most common application of sorting is when a list or table needs to be sorted alphabetically. There are a number of ways to achieve this.
Sorting A-Z
This is quite simple and the sort() function will automatically sort and array of strings A-Z. No other parameter is required in this case.
const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort()
console.log(sort)
// ["Apple","Banana","Mango","Orange"]
Sorting Z-A
This is a little longer to achieve but quite simple. We will pass a function within the sort() that will sort the array into descending order. There are a number of ways to achieve this.
- Reversing the sorted Array To sort the array into descending order, we can simple reverse the array we sorted in ascending order
const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort().reverse()
console.log(sort)
//["Orange","Mango","Banana","Apple"]
- Manually comparing using parameters
You can also run a function within the sort function that checks two items for the greater one and returns a value
const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort((a, b) => (a > b ? -1 : 1))
console.log(sort)
//["Orange","Mango","Banana","Apple"]
We are using inline conditional statements here.
- The localCompare function
The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).
const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort((a, b) => b.localeCompare(a))
console.log(sort)
//["Orange","Mango","Banana","Apple"]
Sorting an Array of Numbers
Sorting numbers in javascript is pretty simple and can be done by running a compare function within the sort()
Sorting numbers in Ascending order
const data = [5,1,6,9,3];
const sort = data.sort((a, b) => a-b)
console.log(sort)
//[1,3,5,6,9]
Sorting numbers in Descending order
const data = [5,1,6,9,3];
const sort = data.sort((a, b) => b-a)
console.log(sort)
//[9,6,5,3,1]
Thanks for reading! Check out my recent Hubpages tutorial: