I have the following structure:
var participant0 = {
name : "",
nickname : "",
number "99999"
} ;
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 = [participant0, participant3, participant1, participant2];
I would like to sort this array by alphabetical letter. First on name, second on nickname. If these two keys doesn't exist, i would like to check the number key and put this element at the end of the sorting list.
Expected result :
var array = [participant2, participant1, participant3, participant0];
(To have sorted object by "aaa", "bbb", "ccc", "9999")
The following code working fine to sort by name or nickname but i don't know how put the item at the end of the sorting list if there is the number key :
fav_list.sort(function(x, y) {
return (x.participant.name || x.participant.nickname).localeCompare(y.participant.name || y.participant.nickname);
});
participant2in the result should be beforeparticipant1? Does reallynickname="aaa" < nickname=""?nickname="aaa" < name="bbb". Are these sort rules strange? Yes, they are, but this is what OP wants.