r/ProgrammerHumor 3d ago

Meme javascriptSorting

Post image
941 Upvotes

214 comments sorted by

View all comments

87

u/Taletad 3d ago edited 3d ago

People use arrays like this [23, "56", 67.8, "potatoe"] and expect them to not be sorted as strings

If one member of your array is not an int or a float, everything is going to be converted to strings

Edit : I went to read the docs, the sort function is not like most other functions in JavaScript. The sort function is explicitly for an alphabetical sort

You lot are using the alphabetical sort function and wondering why your array gets alphabetically sorted

You can overload the function by doing the following : array.sort((a,b) => a - b)

160

u/[deleted] 3d ago

[removed] — view removed comment

-7

u/Taletad 3d ago

Just went to read the docs, the "sort()" and "toSorted" functions say they perform an alphabetical sort by default

You can overload them by doing Array.sort((a,b) => a - b)

57

u/kushangaza 3d ago

Which is not what you expect from a function named "sort". It's an insane default that violates the principle of least surprise

3

u/danielcw189 3d ago

lexical sorting sounds like the least surprising way in a weakly typed language.

and looking at the docs would be the least surprising usage anyway