Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash sorting object by values, without losing the key

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'] 
like image 822
user1340531 Avatar asked Sep 02 '15 09:09

user1340531


People also ask

Does Lodash groupBy preserve order?

groupBy , but it does preserve the order of array-like collections, and that's probably unlikely to change. So the sub-items within groups would retain their original ordering, but the grouped key ordering may change, because they are object properties.

How do I sort with Lodash?

Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee.

Is Lodash sort stable?

This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).


2 Answers

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>
like image 198
nicolas-mosch Avatar answered Sep 21 '22 13:09

nicolas-mosch


I was struggling with a similar problem and I was able to solve it doing some transforms with lodash. For your problem it would be:

let doo = {Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12};  let foo = _.chain(doo)   .map((val, key) => {     return { name: key, count: val }   })   .sortBy('count')   .reverse()   .keyBy('name')   .mapValues('count')   .value();  console.log(foo); // Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2 } 
like image 22
weisk Avatar answered Sep 22 '22 13:09

weisk