Last active
January 25, 2016 11:07
-
-
Save rainder/08f681742f35c4f04271 to your computer and use it in GitHub Desktop.
JS::sort object by value
This file contains hidden or 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
/** | |
* | |
* @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