Skip to content

Instantly share code, notes, and snippets.

@mattd
Last active January 3, 2016 22:39
Show Gist options
  • Save mattd/8529838 to your computer and use it in GitHub Desktop.
Save mattd/8529838 to your computer and use it in GitHub Desktop.
var obj = {
blake: 20,
andrew: 10,
matt: 45
};
var annotated = _.map(obj, function (value, key) {
return {key: key, value: value};
});
var names = _.pluck(_.sortBy(annotated, 'value'), 'key');
@kaw2k
Copy link

kaw2k commented Jan 20, 2014

In a perfect world where underscore is curried, this would work. Also, pretend _.at exists:

var sortByKey = _.compose(_.object, _.sortBy(_.rest), _.pairs);

sortByKey(obj);

As it stands now, chaining will have to do :(

console.log(_.chain(obj)
        .pairs()
        .sortBy(function(val){ return -val[1]})
        .object()
        .value())

@mattd
Copy link
Author

mattd commented Jan 21, 2014

@kaw2k - Niiiice. That's exactly the combo I'd figured I'd missed. I might argue that the sortBy piece is easier to reason about when you're sorting by a keyname - like value. But yours is definitely more compact.

And that curried version is tasty.

(Also, I think you meant _.values().)

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