Last active
August 29, 2015 14:13
-
-
Save PiJoules/7d78a95d53177468d479 to your computer and use it in GitHub Desktop.
Function for sorting an array of objects by their properties
This file contains 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 for sorting an array of objects by their properties. | |
* Based off this stackoverflow post: http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript/4760279#4760279 | |
* | |
* Example: | |
* var People = [ | |
* {Name: "Name", Surname: "Surname"}, | |
* {Name:"AAA", Surname:"ZZZ"}, | |
* {Name: "Name", Surname: "AAA"} | |
* ]; | |
* | |
* People.sort(dynamicSort("Name")); // Sort by name | |
* People.sort(dynamicSort("Surname")); // sort by surname | |
* People.sort(dynamicSort("-Surname")); // sort by surname in reverse | |
* | |
*/ | |
function dynamicSort(property) { | |
var sortOrder = 1; | |
if(property[0] === "-") { | |
sortOrder = -1; | |
property = property.substr(1); | |
} | |
return function (a,b) { | |
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; | |
return result * sortOrder; | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment