var arr = [31,1,144,21,10,19,22,1,3,2,143,190]; arr.sort(); console.log(arr); //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?
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?