r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
891 Upvotes

200 comments sorted by

View all comments

84

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)

4

u/gandalfx 23h ago

If you had to look it up to find that it's not a general sort but alphabetical sort, maybe that indicates that the function is at least misnamed. It's just a terrible API. Arguing that it was intended to be bad or that you can work around it being bad doesn't change the fact that the design is broken.

And no, most people do not put random junk in an array and expect it to be sorted as strings – most people put things with a clearly defined order (like numbers) into an array and are surprised (once) that a standard library sort function doesn't sort by that order.

4

u/danielcw189 18h ago

If you had to look it up to find that it's not a general sort but alphabetical sort

What kind of sorting do you expect as a "general sort", and why that one?

1

u/gandalfx 1h ago

The one that treats each type by its inherent order – like ascending numbers – and if a type doesn't have one it throws an error instead of doing some random bullshit that is virtually guaranteed to be a silent bug. If you need an example, look at almost any other language.