JavaScript offers multiple inbuilt methods for manipulating data structures, one of which is the sort method. The sort()
method is used to order or arrange elements: arithmetic, numeric, ascending, or descending. It is applied to both strings and numbers.
By default, when applied to an array, the sort() method converts the array's elements into strings and then compares the sequence according to UTF-16 (Unicode Transformation Format, 16-bit).
UTF-16 is an encoding scheme used to represent text in computer systems. The codes in UTF-16 range from U+0000 to U+FFFF. For example, the code for the letter a is U+0061, while the code for the letter b is U+0062, and so on.
Sorting an Array of Strings
Suppose you need to sort the array below: you can apply the sort()
method like this:
const names = ['Emily', 'George', 'Charlie', 'Ivan', 'David']; names.sort();
The result will be:
['Charlie', 'David', 'Emily', 'George', 'Ivan']
As you can see, the names array has been sorted alphabetically according to the UTF-16 character encoding scheme. Behind the scenes, the computer simply compares the ASCII values of the first letters of each word to determine their alphabetical order.
Sorting Numbers
When sorting an array of numbers, simply using sort()
will lead to unexpected results because it sorts elements as strings.
const numbers = [-20, 10, 100, -5, 38, 60];
numbers.sort();
console.log(numbers);
// Output: [-20, -5, 10, 100, 38, 60]
From the results, you can see that 100 comes before 38, which is incorrect because, by default, the sort method compares strings. "100" comes before "38" since the character "1" has a lower Unicode code point than "3".
Instead, you need to provide a comparison function to the sort()
method as follows:
array.sort(compareFunction)
The compared function determines the order of operations. It takes two arguments, a
and b
, where a
is the current value and b
is the next value. The function returns a value indicating whether a
should come before b
, b
should come before a
, or they are equal. A negative value means a
should come before b
, a positive value means b
should come before a
, and zero indicates equality.
The compare function looks like this:
function comparedFunction(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
Let’s sort the numbers array again the right way;
const numbers = [-20, 10, 100, -5, 38, 60];
numbers.sort(function(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
console.log(numbers);
The output will be:
[-20, -5, 10, 38, 60, 100]
As you can see, the numbers are correctly sorted in ascending order.
If you need to arrange in descending order, the compare function will look like this:
const numbers = [-20, 10, 100, -5, 38, 60];
numbers.sort(function(a, b) {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
} else {
return 0;
}
});
console.log(numbers);
The output will be:
[100, 60, 38, 10, -5, -20]
You can simplify the compare function as shown below to achieve the same result.
const numbers = [-20, 10, 100, -5, 38, 60];
numbers.sort((a, b) => a - b);
console.log(numbers);
If you need to see the comparing process in action, you can log each iteration like this:
const numbers = [-20, 10, 100, -5, 38, 60];
numbers.sort((a, b) => {
console.log(`Comparing ${a} and ${b}`);
return b - a;
});
Here is the result:
Conclusion
In summary, the sort()
method in JavaScrip makes it easy to organize your array precisely as you want it and will come in handy when you want to sort dates, prices, e.t.c