Last active
July 19, 2016 06:06
-
-
Save kevinweber/70b80180ae30ab34c62d94589bf4a62f to your computer and use it in GitHub Desktop.
Sort objects of an object based on one of their common 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
/** | |
* 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