Summary: In this tutorial, we will learn how to use the JavaScript sort() method from beginner to pro. Sorting arrays of strings, numbers, and when to use comparator functions.
Let's check the default behaviour of the sort() method
const letters = ['s','p','c','a']
const sortedLetter = letters.sort()
console.log(sortLetter) //['a','c','p','s']
Using lowercase alphabet as elements of our array, the sort method works fine. It arranges the elements in ascending order alphabetically.
Let's tone it up a bit by changing our 'p' to a 'P' (uppercase).
const letters = ['s','P','c','a']
const sortedLetter = letters.sort()
console.log(sortLetter) //['P','a','c','s']
Here we notice the 'P' is not at the end of our array again.
It is now the first element of our array.
Why?
Before we go any further let's look more into how the sort method works behind the scene.
According to the above definition, the javascript sort method uses UTF-16 code unit values to sort the array elements.
To understand this, even more, we can log out the UTF-16 code values of each element in our array list.
//using forEach method
const letters = ['s','P','c','a']
letters.forEach((letter)=>{
console.log(letter + ' : ' + letter.charCodeAt(0))
})
// s : 115
// P : 80
// c : 99
// a : 97
N:B: charCodeAt() returns integer btw 0-65535 representing the UTF-16 code unit of a given index
In the result commented above, we can see each element of our array, and their UTF-16 code value
Here is why 'P' came first in our array?
The P alphabet has a UTF-16 code value of 80. which happen to be the lowest in our array. And remember our array is been sorted in ascending order
Sorting Numbers
const numbers = [2,5,100,4]
console.log(numbers.sort())
//[100,2,4,5]
Here we will notice 100 came first in the array after sorting.
Remembering our sort method defined above.
The sort method converts elements into strings and UTF-16 code before comparing and then sorting
We can check the UTF-16 code of our number array too, to know why 100 came first
const numbers = [2,5,100,4]
numbers.forEach((number)=> {
console.log(number + ' : ' + String(number).charCodeAt(0))
})
// 2 : 50
// 5 : 53
// 100 : 49
// 4 : 52
N:B: To use the charCodeAt on numbers we need to convert them to strings String(number).
Now we know why 100 came first; It has the smallest UTF-16 code value
And we want 100 to be at the back of our array where it belongs using ascending order.
To fix this, you need to pass a compare function to the sort() method. The sort() method will use the compare function to determine the order of elements in the array
Javascript sort() method accepts an optional argument.
Which is a function that compares the elements of the array, known as the comparator functions.
This comparator function accepts two arguments. Then returns a value that determines the sorting order.
Syntax of the compare function:
function compare(a,b) {
// ...
}
When sort() compares two elements of an array, it sends the elements to the comparator function and sorts the elements according to the returned value (negative, zero, positive).
The way it works is, it takes a custom 'a' and 'b' parameter which in our array will represent a=2, b=5 at first.
The compare function works using a three-way comparison technique. meaning it checks if the 'a' value is lesser, greater, or equal to the 'b' value
The sort method will sort elements based on the return result value of the compare function with the following rules:
If the return value is
- Negative: If compare(a,b) is less than zero (-ve), the element a is smaller than b In other words, a will come first.
- Positive: If compare(a,b) is greater than zero (+ve), the sort() method sorts a as a bigger number than b. b will come first.
- Zero: If compare(a,b) returns zero (=), the sort() method considers a equals b and leaves their positions unchanged. And moves to compare the next elements
Sorting numbers in ascending order
let scores = [2,5,100,4];
scores.sort((a, b) => {
console.log(a,b)
return a - b
});
5 2
100 5
4 100
4 5
4 2
[2, 4, 5, 100]
The console log here shows how the compare function picks and compare each element of our array.
const numbers = [2,155,100,102,122]
const sortNumbers = numbers.sort((a,b)=>{
if(a>b){
return 1
}else if(a<b){
return -1
}else{
return 0
}
})
console.log(sortNumbers)
// [2, 100, 102, 122, 155]
In the comparator function above, If the value of a is greater than the value b.
Then the element b would come before a because it returns a positive (+ve)
but if a is lesser than b. Then a would come before b, because it return a negative here (-ve)
Where a return of zero indicates (=) equal to.
Now that we know our sort() method alot better.
Let's flex our muscles a bit.
What if we wanted to arrange our array in descending order?
simply we reverse our code like this
const numbers = [2,5,100,4]
const sortNumbers = numbers.sort((a,b)=> {return b-a})
console.log(sortNumbers)
// [100, 5, 4, 2]
Explaining the above code:
Here we are returning b - a
e.g 5- 2= 3
Remembering how the sort comparator works;
Stating what is important to the sort method function is that we return a
Positive || Negative || Zero value from our comparator function
So with this function statement, if we return a positive value this also means that b comes first before a
And a negative means a comes before b