Method of sorting an array is defined in
What’s The Problem?
Array type, so that you don’t have to write it by yourself.
Two things we can know from the above example are: Firstly,
String type is sorted in an alphabetic order. Secondly,
sort() method changes the original array rather than generating a new array.
But it’s not sorted in an alphabetic order in fact.
It compares by each character’s ASCII code so that uppercase letters are always smaller than lowercase ones.
Another thing you need to be careful with is when you sort an array with numbers.
By default, the
sort() method converts everything into
12 should be thought as larger than
7.4, then, how to sort the whole array?
String and compare letter by letter in ASCII code order. So
true is converted to
false is converted to
"false" when comparing.
Sorting arrays with numbers only is still a very common need. So how can I sort them by comparing numbers’ value?
Pass a comparing function to it!
Now, you get what you wanted. :grinning:
What happens here is that
compare function takes two element and returns a negative number if
a is smaller than
a is equal to
b, a positive number if
a is larger than
Comparing function is also useful when we compare objects. Let’s say that we want to sort people by their
id rather than their
name, we can define a function to compare people by
What if we sort
Chrome and Opera:
[4, "Red", "$200", "white", false, 0.3, true, 7.4, 12];
[false, 0.3, true, 4, "Red", "$200", "white", 7.4, 12];
["Red", "$200", false, 0.3, true, 4, "white", 7.4, 12].
This is so weird! :scream:
a - b is calculated in
compare so that every element in
everything is converted to
Number when comparing and then do the minus operation. As
NaN all, comparing function
NaN when they compare to any other element. With the existance of this
NaN, the behavior of
Array.prototype.sort is not defined in the ECMA Specification, so it depends on each platform’s implementation.
comparefn(a,b)always returns the same value
vwhen given a specific pair of values
bas its two arguments. Furthermore,
NaN. Note that this implies that exactly one of
a <CF b,
a =CF b, and
a >CF bwill be true for a given pair of a and b.
The lesson learned here is that the behavior of sorting with a comparing function that will return
NaN is unpredictable and you should be careful when choosing a suitable comparing function. Again, it’s not a good idea to put everything with different types all together in the same array.