Lodash sorting object by values, without losing the key

user1340531 picture user1340531 · Sep 2, 2015 · Viewed 23.5k times · Source

Let's say I have an object:

{Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}

And I need to sort it by value. What I'm looking to get is:

{Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

I'd like to use lodash for it. When I use _.sortBy it doesn't retain the keys how ever:

_.sortBy({Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}).reverse();
// [17, 12, 8, 5, 2]

Hell, I'd even settle for just the array of keys, but still sorted by the value in the input:

['Derp', 'Herp', 'Foo', 'Asd', 'Qwe']

Answer

nicolas-mosch picture nicolas-mosch · Jan 26, 2017

This worked for me

o = _.fromPairs(_.sortBy(_.toPairs(o), 1).reverse())

Here's an example:

var o = {
  a: 2,
  c: 3,
  b: 1
};
o = _.fromPairs(_.sortBy(_.toPairs(o), 1).reverse())
console.log(o);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>