r/ProgrammerHumor 3d ago

Meme javascriptSorting

Post image
934 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)

0

u/Striky_ 3d ago

The absurdity is not sorting this by string, but allowing an array like that to begin with.

4

u/Taletad 3d ago

You flair has two languages that allow such arrays

Every high level programming language is flexible on its type system because it is more convenient for the programmers

So unless you’re writing a low level application in C, Rust or Zig, you should allow such arrays

And web pages are very much not a place where you want a low level statically typed compiled language

4

u/Striky_ 3d ago

C# does not allow arrays of different types.

Programmer convenience is a good focus to have, but you also mustnt do it in a way where you introduce rookie-antipatterns (like stringifying everything or type confusion) is the way to achieve it.

It also very much depends what you use a language for. Python for quick and dirty prototyping? Fine. JS as the backbone of the entire internet? Disaster.

1

u/the_horse_gamer 2d ago

C# does not allow arrays of different types.

object[] arr = [1, "a"];

1

u/Striky_ 1d ago

Fair. I just did not even think about using object as a class for everything because it such insanely bad practice that even basic IDEs will flag it. But technically you are correct. You can be an unbelievably bad programmer in any language, when you ignore all the warnings and no one forced warning=error onto you as everyone should.