Created
August 16, 2018 14:53
-
-
Save nara-l/ee56256602e1069addb2481416ad847f to your computer and use it in GitHub Desktop.
Javascript better sort Array of Objects
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 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; | |
| } | |
| } | |
| // usage | |
| So you can have an array of objects like this: | |
| var People = [ | |
| {Name: "Name", Surname: "Surname"}, | |
| {Name:"AAA", Surname:"ZZZ"}, | |
| {Name: "Name", Surname: "AAA"} | |
| ]; | |
| //...and it will work when you do: | |
| People.sort(dynamicSort("Name")); | |
| People.sort(dynamicSort("Surname")); | |
| People.sort(dynamicSort("-Surname")); | |
| // from https://stackoverflow.com/a/4760279/851056 | |
| // covers multiple parameters as well |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment