Skip to content

Instantly share code, notes, and snippets.

@shalakolee
Created April 25, 2017 23:13
Show Gist options
  • Save shalakolee/0708aaa93b208ba2beb1f11bfdab4f00 to your computer and use it in GitHub Desktop.
Save shalakolee/0708aaa93b208ba2beb1f11bfdab4f00 to your computer and use it in GitHub Desktop.
Javascript - Sorting Objects Function
/**
* This javascript function will sort an object of objects by converting it to an array, ordering it, and pushing it back into an object
* usage: mySortedObject = customObjectSort(object,"objectKey");
*/
function customObjectSort(data, attr) {
var arr = [];
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var obj = {};
obj[prop] = data[prop];
obj.tempSortName = data[prop][attr];
arr.push(obj);
}
}
arr.sort(function(a, b) {
var at = a.tempSortName,
bt = b.tempSortName;
return at < bt ? 1 : ( at > bt ? -1 : 0 );
});
var result = [];
for (var i=0, l=arr.length; i<l; i++) {
var obj = arr[i];
delete obj.tempSortName;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var id = prop;
}
}
var item = obj[id];
result.push(item);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment