Sort() in javascript

var arr = [31,1,144,21,10,19,22,1,3,2,143,190];

//this gives me 
//[ 1, 1, 10, 143, 144, 19, 190, 2, 21, 22, 3, 31 ]
//which is not from the smallest to the biggest
//so, sort() function sort out array according to what?

I was wondering the above question then I saw this on W3C article about sort() in javascript : here’s the quote:

By default, the sort() function sorts values as strings.

This works well for strings (“Apple” comes before “Banana”).

However, if numbers are sorted as strings, “25” is bigger than “100”, because “2” is bigger than “1”.

So the sort() function will treat every element inside the array as a string when sorting out elements, so when the elements are words, it will sort out those words from their initials and it will sort them out alphabetically.

But when it comes to numbers, sort() will treat those numbers as strings.
So instead of comparing 1 and 2 it becomes comparing “1” and “2”. And it still sorts them out according to their initials. Therefore the result you get is everything that starts with 1 1st, then everything starts with 2 etc etc.

Is my understanding correct?

This will sort you out(no pun intended). Ps: You’ll need compare function as a parameter. Citing for compare function: “Specifies a function that defines the sort order. If omitted, the array is sorted according to each character’s Unicode code point value, according to the string conversion of each element.”


I suggest reading through the sort method’s documentation. There, you will understand how to use a callback function to sort the elements differently than the default sorting by converting the element values to strings first.