javascript - Difference between sort(), sort(function(a,b){return a-b;}); and sort(function(a,b){...}) -


i trying understand how sort() works , how supposed use it.

i did research (google) , went through similar questions here on stackoverflow, there still few things not 100% clear me.

so understanding far following:

there are:

sort() without parameters: sorts simple arrays of string values alphabetically , in ascending order

e.g.

// sort alphabetically , ascending: var myarr=["bob", "bully", "amy"] myarr.sort() // array becomes ["amy", "bob", "bully"] 


sort() function parameter: sorts objects in arrays according properties; items are, however, compared numbers

myarr.sort(function(a,b) {      return - b;  }); 


sort() function parameter: sorts objects in arrays according properties; items can 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; }); 


tried sorting following array 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 since doesn't know on property sort    /*  myarr.sort(function(a, b) {      return (a.sortnumber - b.sortnumber); // sorts array      return (a.name - b.name); // doesn't sort array  });  */    /*  // sorts array when use name property 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 fiddle.

so, questions are:

  1. is understanding correct?
  2. is there missing?
  3. if third case works @ times, can stick or other 2 cases more efficient in way or have advantages third case?

i appreciate if elaborate on above. thank you.

ok, after additional research, going through mdn documentation, , arraysort , arraysort2 links, found helpful, created slide of use else, posting here. thank answers!

enter image description here


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -