Skip to content

Instantly share code, notes, and snippets.

@growdigital
Created February 29, 2012 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save growdigital/1938970 to your computer and use it in GitHub Desktop.
Save growdigital/1938970 to your computer and use it in GitHub Desktop.
Sort an Array of Objects by Property Using sort(fn)
[
{ name: "Robin Van Persie", age: 28 },
{ name: "Theo Walcott", age: 22 },
{ name: "Bacary Sagna", age: 26 }
].sort(function(obj1, obj2) {
// Ascending: first age greater than the previous
return obj1.age - obj2.age;
});
// Returns:
// [
// { name: "Theo Walcott", age: 22 },
// { name: "Bacary Sagna", age: 26 },
// { name: "Robin Van Persie", age: 28 }
// ]
// via http://davidwalsh.name/array-sort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment