wawanopoulos wawanopoulos - 27 days ago 4
Javascript Question

Sorting objects in an array by a field value (if exist)

I have the following structure:

var participant1 = {
name : "bbb",
nickname : "",
} ;

var participant2 = {
name : "",
nickname : "aaa"
} ;

var participant3 = {
name : "ccc",
nickname : ""
} ;


And i have an array which contain instances of structure :

var array = [participant3, participant1, participant2];


I would like to sort this array by alphabetical letter. First on name, but if name doesn't exist, i would like to use nickname to sort. The final result will be :

var array = [participant2, participant1, participant3];


(To have sorted object by "aaa", "bbb", "ccc")

Answer

You need to create a compare function and then use .sort()

function compare(a,b) {
  if (a.name< b.name)
     return -1;
  else if (a.name> b.name)
    return 1;
  else
   {
      if (a.nickname< b.nickname)  return -1;
      else return 1;
   }
}

array.sort(compare);
Comments