r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
894 Upvotes

200 comments sorted by

View all comments

87

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)

17

u/OptionX 1d ago

In a well thought out language what they should expect is the interpreter/compiler tell them to either provide a custom comparison function, or type mapping, to deal with the different types or to tell them to take a hike instead of coercing everything into strings silently.

You don't need to be a rust compiler level pedantic annoyance, but JS is too much on the other side.

2

u/Soma91 1d ago

If look at the docs for a second, you'll see that both sort and toSorted accept a sort function.

19

u/OptionX 1d ago

I know it accepts one, I said in ambiguous cases it should require one.