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 stackoverflow, but there are still a few things not 100% clear to me.
So my understanding so far is the following:
There are:
sort() without parameters: sorts only simple arrays of String values alphabetically and in ascending order
E.g.
// 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; the items are, however, 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; the 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 sorting the following 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"
}];
//myArr.sort(); // doesn't do anything since it doesn't know on what property to sort
/*
myArr.sort(function(a, b) {
return (a.sortnumber - b.sortnumber); // sorts array
return (a.name - b.name); // doesn't sort array
});
*/
/*
// sorts array even when I use name as property to sort on
myArr.sort(function(a, b) {
if (a.sortnumber < b.sortnumber) return -1;
else if (a.sortnumber > b.sortnumber) return 1;
return 0;
});
*/
console.log(myArr);
Here is also a fiddle.
So, my questions are:
I would really appreciate it if anyone could elaborate on the above. Thank you.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With