Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active July 19, 2016 06:06
Show Gist options
  • Save kevinweber/70b80180ae30ab34c62d94589bf4a62f to your computer and use it in GitHub Desktop.
Save kevinweber/70b80180ae30ab34c62d94589bf4a62f to your computer and use it in GitHub Desktop.
Sort objects of an object based on one of their common properties
/**
* Sort objects of an object based on one of their common properties
*
* Call it like this:
* mySortedObject = sortObjectWithObjects(myObject, "name");
*
* To store ...
*
var myObject = [{
name: "StringC",
otherProp: "One"
}, {
name: "StringA",
otherProp: "Two"
}, {
name: "StringB",
otherProp: "Three"
}];
*
* as ...
*
var myObject = [{
name: "StringA",
otherProp: "Two"
}, {
name: "StringB",
otherProp: "Three"
}, {
name: "StringC",
otherProp: "One"
}];
*
*/
function sortObjectWithObjects(object, nodeName) {
return object.sort(function (a, b) {
if (a[nodeName] > b[nodeName]) {
return 1;
} else if (a[nodeName] < b[nodeName]) {
return -1;
}
return 0;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment