0

(Please excuse any errors - this is my first post and I am also relatively new to Javascript)

I'm trying to sort an array of objects by a specific property value in Javascript. I have several objects as follows:

var Obj1 = {firstName: "John", lastName: "Doe", age: 46};
var Obj2 = {firstName: "Paul", lastName: "Smith", age: 22};
var Obj3 = {firstName: "Trent", lastName: "Johnson", age: 81};

And I have saved these into an array for easy access:

var Arr = [Obj1, Obj2, Obj3];

I wish to sort these objects within the array by age, giving:

Arr = [Obj2, Obj1, Obj3];

whilst still keeping the integrity of each object (ie. Obj1 still contains John, Doe and 46).

From my research I haven't seen anyone address this situation in a simple manner.

Thank you for any direction you might be able to give me!

MSTTm
  • 293
  • 3
  • 7
  • 18

1 Answers1

1

You use a custom callback with the array method .sort().

Arr.sort(function(a, b) {
    return a.age - b.age;
});

MDN reference page on .sort().


And, here's a working snippet:

var Obj1 = {firstName: "John", lastName: "Doe", age: 46}; 
var Obj2 = {firstName: "Paul", lastName: "Smith", age: 22}; 
var Obj3 = {firstName: "Trent", lastName: "Johnson", age: 81};

var Arr = [Obj1, Obj2, Obj3];

Arr.sort(function(a, b) {
    return a.age - b.age;
});

document.write(JSON.stringify(Arr));
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Absolutely perfect - exactly what I wanted! Thank you so much for your help! (Apologies for the duplicate - can't believe I missed that) – MSTTm Jun 23 '15 at 03:35