Skip to content

Instantly share code, notes, and snippets.

@icodejs
Created August 31, 2012 10:49
Show Gist options
  • Save icodejs/3551386 to your computer and use it in GitHub Desktop.
Save icodejs/3551386 to your computer and use it in GitHub Desktop.
JS: Sort objects within an array
// http://davidwalsh.name/array-sort
// If you provide a function expression to the sort method, you can sort
// objects within the array using simple logic. Let's say you have an
// array of objects representing persons and you want to sort them by age.
// Oh yes, it can be done, and quite easily:
[
{ name: "Robin Van Persie", age: 28 },
{ name: "Theo Walcott", age: 22 },
{ name: "Bacary Sagna", age: 26 }
].sort(function(obj1, obj2) {
// Ascending: first age less 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 }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment