I am trying to understand exactly how sort () works and how I should use it.
I did some research (google) and looked at similar questions here on stackoverflow, but there are a few more things that are 100% clear to me.
So, so far I understand the following:
There is:
sort () without parameters : sorts only simple arrays String values in alphabetical order and ascending order
eg.
// sort alphabetically and ascending: var myArr=["Bob", "Bully", "Amy"] myArr.sort() // Array now becomes ["Amy", "Bob", "Bully"]
sort () with a function as a parameter : sorts objects in arrays according to their properties; elements, however, are compared as numbers
myArr.sort(function(a,b) { return a - b; });
sort () with a function as a parameter : sorts objects in arrays according to their properties; items can be numbers or strings
myArr.sort(function(a, b) { if (a.sortnumber < b.sortnumber) return -1; else if (a.sortnumber > b.sortnumber) return 1; return 0; });
I tried to sort the next array with all these 3 sort () functions.
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" }];
There is also a violin.
So my questions are:
- Do I understand correctly?
- Is there something I am missing?
- If the third case always works, can I always stick to it or the other two cases are more effective in some way or have any advantages for the third case?
I would really appreciate it if anyone could dwell on this in more detail. Thanks.
source share