Skip to content

Instantly share code, notes, and snippets.

@nara-l
Created August 16, 2018 14:53
Show Gist options
  • Save nara-l/ee56256602e1069addb2481416ad847f to your computer and use it in GitHub Desktop.
Save nara-l/ee56256602e1069addb2481416ad847f to your computer and use it in GitHub Desktop.
Javascript better sort Array of Objects
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