.sort method in JavaScript may not sort numbers the way you would expect.
Deepanshu Gupta
Posted on March 24, 2023
In JavaScript, the array.sort() method sorts the array.
Now, the data type in the array could be anything, either numbers or strings.
When we talk about sorting through an array that contains a string, .sort() method seems to work just fine. There is a caveat though on how this sorting actually works.
Behind the scenes of sorting
.sort() works in a peculiar way, i.e. it converts the initial letter(s) of the string into equivalent ASCII characters and then, the converted values are compared, and therefore sorted.
By value, capital letters have ASCII values with low number equivalent, therefore considered small, and they appear first then the small case letters since the default method is to sort in ascending order.
const names = ['joker', 'batman', 'catwoman'];
names.sort(); // => ['batman', 'catwoman', 'joker']
In the case of numbers, sorting works not as you would expect
Same way, the numbers are converted into their equivalent ASCII characters values and then the new equivalent values are compared, similar to how a dictionary algorithm works, which therefore fetches us wrong results. Therefore to expect the right behaviour from sort method in case of sorting of numbers, we pass a callback function in the .sort() as parameters, which return either a-b ( for ascending order of sorting ) or return b-a for descending order of sorting.
Please refer to the examples below to have a better understanding of how this works.
const numbers = [10, 5, 11];
numbers.sort(); // => [10, 11, 5]
const numbers = [10, 5, 11];
numbers.sort((a, b) => a - b); // => [5, 10, 11]
Posted on March 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.