Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.