Created
July 15, 2013 20:45
-
-
Save scarstens/6003301 to your computer and use it in GitHub Desktop.
Sort array of objects by a property in each object
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
| function sortObjectBy(property) { | |
| var sortOrder = 1; | |
| if(property[0] === "-") { | |
| sortOrder = -1; | |
| property = property.substr(1, property.length - 1); | |
| } | |
| return function (a,b) { | |
| var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; | |
| return result * sortOrder; | |
| } | |
| } | |
| /* Example usage: */ | |
| var distances = []; | |
| distances.push({marker:'Arizona', distance: 300}) | |
| distances.push({marker:'Utah', distance: 100}) | |
| distances.push({marker:'Washington', distance: 600}) | |
| distances.push({marker:'California', distance: 200}) | |
| distances.sort(sortObjectBy("distance")); | |
| console.log(distances); | |
| /* Note they are now sorted by distance instead of the order above. */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment