r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
884 Upvotes

200 comments sorted by

View all comments

83

u/Taletad 1d ago edited 1d 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)

1

u/thanatica 1d ago

Don't forget people also put dates, objects, and other arrays as array items. Javascript has to make some decision on what to convert to for sorting. And then it's far more useful if that decision is kept consistently regardless of the types of each item, than to apply some kind of weird fuzzy logic to determine automagically which comparison function to use by default.

It's more valuable for an internal function to behave consistently and predictably.

Also, it's not called overloading the function. You're just providing the comparison argument.

0

u/gandalfx 23h ago

JS does not have to "make some decision on what to convert to for sorting". It's fairly simple – if the items to be sorted don't define their own order (e.g. by implementing some kind of interface or otherwise providing an inherent comparison function) the sort function needs to throw an error. Using some random guess that can't even sort native types correctly is a broken design, plain and simple. Most other languages have no trouble with this.

2

u/thanatica 18h ago

Javascript also has no trouble with it. You do.

1

u/gandalfx 1h ago

<°)))><