1

I have the following structure:

var participant1 = {
    name : "aaa",
} ;

var participant2 = {
    name : "bbb",
} ;

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

And i have an array which contain instances of structure :

var array = [participant3, participant1, participant2];

How can i sort the array by alphabetical letter of name attribute to get this result :

var array = [participant1, participant2, participant3];
wawanopoulos
  • 9,614
  • 31
  • 111
  • 166
  • 2
    Your question is not clear, are you saying that you want to sort by *name of variable* or by the *name property within the object contained in the variable*? – Rory McCrossan Feb 18 '15 at 16:23
  • You can't; the concept doesn't make much sense. The names of the variables to which those object references are assigned are not in any way an intrinsic part of the objects. – Pointy Feb 18 '15 at 16:23

1 Answers1

5

Using sort method:

array = array.sort( function(a,b) {
    if (a.name > b.name) {
        return 1;
    }
    if (a.name < b.name) {
        return -1;
    }
    return 0;
});
antyrat
  • 27,479
  • 9
  • 75
  • 76