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
First of all, you did a good research and covered almost all possible cases, and you can find the MDN documentation here
You just missed the case of Sorting non-ASCII characters
For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English: use String.localeCompare. This function can compare those characters so they appear in the right order.
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
items.sort(function (a, b) {
return a.localeCompare(b);
});
// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
I think, you would like to combine the sort criteria, like this example which sort by name forst and then by number. Please watch 'John'
.
var myArr = [{ "sortnumber": 9, "name": "Bob" }, { "sortnumber": 5, "name": "Alice" }, { "sortnumber": 4, "name": "John" }, { "sortnumber": 3, "name": "James" }, { "sortnumber": 7, "name": "Peter" }, { "sortnumber": 6, "name": "Doug" }, { "sortnumber": 2, "name": "Stacey" }, { "sortnumber": 14, "name": "John" }, { "sortnumber": 12, "name": "John" }];
myArr.sort(function (a, b) {
return a.name.localeCompare(b.name) || a.sortnumber - b.sortnumber;
});
console.log(myArr);
Ok, so after some additional research, going through the MDN documentation, and the arraysort and arraysort2 links, which I found very helpful, I created a slide that could probably be of use to someone else, so I am posting it here. Thank you all for your answers!
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);
});