Skip to content

Instantly share code, notes, and snippets.

@medfreeman
Forked from colingourlay/example.js
Created May 15, 2017 23:19
Show Gist options
  • Select an option

  • Save medfreeman/203b10bd9beef1d89a035b336bb038e4 to your computer and use it in GitHub Desktop.

Select an option

Save medfreeman/203b10bd9beef1d89a035b336bb038e4 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.
_.mixin({
'sortKeysBy': function (obj, comparator) {
var keys = _.sortBy(_.keys(obj), function (key) {
return comparator(obj[key], key);
});
return _.object(keys, _.map(keys, function (key) {
return obj[key];
}));
}
});
@medfreeman
Copy link
Author

medfreeman commented Nov 16, 2017

_.mixin({
  sortByKeys: (obj, comparator) =>
     _(obj).toPairs()
    .sortBy(
      pair => comparator ? comparator(pair[1], pair[0]) : 0
    )
    .fromPairs()
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment