Created
August 31, 2012 10:49
-
-
Save icodejs/3551386 to your computer and use it in GitHub Desktop.
JS: Sort objects within an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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