I am trying to understand how exactly sort() works and how I am supposed to use it.
I did some research (google) and went through the similar questions here on stackover
According to Array reference (http://www.w3schools.com/jsref/jsref_sort.asp):
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
So your first understanding about sort()
is correct. However, the second and third are not yet correct. First of all, they are both the same case, which is providing a sorting function to the sort()
method. This method should compare the a
and b
, and return negative, zero, or positive values, indicating if a
is less than, equals, or greater than b
. So for example, you can still compare your myArr
using the name
property like this:
myArr.sort(function(a,b) {
return a.name.localeCompare(b.name);
});