Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  1. Is my understanding correct?
  2. Is there anything that I am missing?
  3. If the third case works at all times, can I always stick to it or are the other two cases more efficient in some way or have any advantages to the third case?

I would really appreciate it if anyone could elaborate on the above. Thank you.

like image 887
Setily Avatar asked Aug 29 '16 09:08

Setily


1 Answers

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!

enter image description here

like image 150
Setily Avatar answered Sep 27 '22 17:09

Setily