Like any programming language, JavaScript also provides ways to sort arrays. Different JavaScript engines implement this method using different sort algorithms. For example –
Safari: Quicksort, Merge Sort, or Selection Sort
V8: Quicksort, or Insertion Sort
Firefox: Merge Sort
But in reality, it doesn’t really matter much as long as the arrays are getting sorted.
Note – I am putting my JavaScript Developer study notes here.
The prototype for Sort method available in Array class is:
Array.sort([compareFunction])
Normally a callback function is passed which makes the sorting logic i.e. how the two numbers will be compared. This callback function should take two parameters i.e. param1 and param2 and works like this –
callback function will return zero when both param1 and param2 are treated as equal
callback function will return 1 when both param1 is smaller than param2
callback function will return 11 when both param2 is smaller than param1
Note – In default sorting, param1 and param2 are always converted into Strings and then they will be sorted alphabetically.
For example, if we consider the below example
letnumbers = [100, 23, 45, 12, 99];
letsortedNumbers =numbers.sort();
console.log(sortedNumbers);
Output:
[ 100, 12, 23, 45, 99 ]
But that’s not the correct sorting. The reason behind is that numbers here are converted into Strings and then sorted alphabetically due to default sorting.
To solve this we need to pass the callback function which will define the comparison logic. Below is the modified code –