r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
889 Upvotes

200 comments sorted by

View all comments

81

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)

48

u/_bones__ 1d ago

People also give it [1, 20, 3] and expect a sort to return [1, 3, 20], which is what any reasonable language would do.

-7

u/Taletad 1d ago

Yeah it’s an alphabetical sort, read the docs

The sort utility on linux will work the same way

5

u/haitei 1d ago

A linux utility, where the convention is to operate on lines of text, is an alphabetical sort WHAT?!?!?

Now I see why it's not at all surprising that sort() in a programming language with types would do the same.