0
itemsArr.sort(function (a, b) {
    return a.innerHTML == b.innerHTML ? 0 : (a.innerHTML > b.innerHTML ? 1 : -1);
});

I'd like to know how this function could be written with if & else syntax

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
YoniGeek
  • 4,053
  • 7
  • 27
  • 30

4 Answers4

3
itemsArr.sort(sortFunction);
function sortFunction (a, b) { 
  if (a.innerHTML == b.innerHTML) return 0;
  else if (a.innerHTML > b.innerHTML) return 1;
  else return -1; 
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

That would look like this:

itemsArr.sort(function(a, b) {
  if (a.innerHTML == b.innerHTML) {
    return 0;
  } else if (a.innerHTML > b.innerHTML) {
    return 1;
  } else {
    return -1;
  }
});

You can also write it without else, as the return will exit the function:

itemsArr.sort(function(a, b) {
  if (a.innerHTML == b.innerHTML) return 0;
  if (a.innerHTML > b.innerHTML) return 1;
  return -1;
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0
function isGreater(a,b){
   if(a.innerHTML == b.innerHTML){
     return 0;
   } else if(a.innerHTML > b.innerHTML){
          return 1;
   }else{
       return -1;
   }
}

But why you want to do this?

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • Im learning about this subject and I saw this thread: http://stackoverflow.com/questions/282670/easiest-way-to-sort-dom-nodes/5854834#5854834 – YoniGeek May 02 '11 at 09:46
  • @YoniGeek: then you should comment @nickf about this rather than giving answer and then after asking question here. – Harry Joy May 02 '11 at 09:59
0
function(a, b) {
   returnType returnValue;

   if(a.innerHTML == b.innerHTML){
    returnValue = 0;
   }else if(a.innerHTML > b.innerHTML){
    returnValue = 1
   }else{
    returnValue = -1
   }

   return returnValue;
}
fleur
  • 115
  • 1
  • 12