Skip to content

Instantly share code, notes, and snippets.

@examinedliving
Forked from colingourlay/example.js
Created January 5, 2018 18:42
Show Gist options
  • Save examinedliving/6eaba22c85d981a7b5aff6788fd5c669 to your computer and use it in GitHub Desktop.
Save examinedliving/6eaba22c85d981a7b5aff6788fd5c669 to your computer and use it in GitHub Desktop.
Lodash / Underscore sort object keys. Like _.sortBy(), but on keys instead of values, returning an object, not an array. Defaults to alphanumeric sort.
var obj = {b: 3, c: 2, a: 1};
_.sortKeysBy(obj);
// {a: 1, b: 3, c: 2}
_.sortKeysBy(obj, function (value, key) {
return value;
});
// {a: 1, c: 2, b: 3}
_.mixin({
'sortKeysBy': function (obj, comparator) {
var keys = _.sortBy(_.keys(obj), function (key) {
return comparator ? comparator(obj[key], key) : key;
});
return _.object(keys, _.map(keys, function (key) {
return obj[key];
}));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment