DEV Community

loading...

Default Javascript Array Sorting

siamcr7 profile image Jamil Siam ใƒป1 min read

I was recently solving a simple programming problem with TS, where I had to sort an array of integers in ascending order as part of the solution. So, naturally, I resorted to the array.sort() method.

To my surprise, I was getting a wrong answer verdict even though I was certain that my solution was correct. It turned out that TS (or rather JS) array default sorting behaviour has a quite confusing caveat.

To get a better understanding of what I am talking about, let's see the following code:

Snippet 1:

[10, 2, 1].sort()
Enter fullscreen mode Exit fullscreen mode

Snippet 2:

['10', '2', '1'].sort()
Enter fullscreen mode Exit fullscreen mode

In C++/C#/Java/C, the snippet 1 would return [1, 2, 10] and snippet 2 would return ['1', '10', '2'].

However, in JS world, both of the snippets would return the same order ([1, 10, 2] and ['1', '10', '2'] respectively) because in JS the default behaviour is to convert the values into strings and then run sorting (details).

For Snippet 1 to work correctly in JS:

[10, 2, 1].sort((a, b) => a - b)
Enter fullscreen mode Exit fullscreen mode

That's it for today!

PS. This is my first post in dev.to or in any platform
PSS. If you are interested to know about solving programming problems in TS feel free to check out my repo.

Discussion (0)

pic
Editor guide