Skip to content

Instantly share code, notes, and snippets.

@rainder
Last active January 25, 2016 11:07
Show Gist options
  • Save rainder/08f681742f35c4f04271 to your computer and use it in GitHub Desktop.
Save rainder/08f681742f35c4f04271 to your computer and use it in GitHub Desktop.
JS::sort object by value
/**
*
* @param {object} object An object to sort
* @param {boolean} [reverse=false] Sort direction
* @returns {{}}
*/
function sortObject(object, reverse) {
var result = {};
(function () {
// transform object to an array
var sortable = [];
for (var i in object) {
if (object.hasOwnProperty(i)) {
sortable.push([i, object[i]]);
}
}
return sortable;
})().sort(function (a, b) {
// sort an array
return (a[1] - b[1]) * (reverse ? -1 : 1);
}).forEach(function (item) {
// transform sorted array to an object
result[item[0]] = item[1];
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment