Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort object by value with lodash

I have an object that looks like this:

var unsorted = {a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1}

And I am interested in sorted it in descending order with lodash, so the expected result should be:

var sortd = {b: 1, g: 1,c: 2, e: 3, d: 4, f: 6, a: 15}

I have tried using lodash orderBy but it gives an array of just the values sorted.

_.orderBy(tempCount, Number, ['desc'])

//Result
[1,1,2,3,4,6,15]
like image 865
Dave Kalu Avatar asked Feb 04 '19 16:02

Dave Kalu


2 Answers

You could build a new object with the sorted key/value pairs.

The actual standard or the order of properties:

  • sort index like keys first, in order
  • keep all other keys in insertation order

For a complete control over the order, take an array with the keys an take it as sorted accessor for the values.

var unsorted = { a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1 },
    sorted = _(unsorted)
        .toPairs()
        .orderBy([1], ['desc'])
        .fromPairs()
        .value()
        
console.log(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Descending sort with _.orderBy by using a the last parameter for a specific order, instead of _.sortBy, which only allows to sort ascending.

var unsorted = { a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1 },
    sorted = _(unsorted)
        .toPairs()
        .orderBy(1, 'desc')
        .fromPairs()
        .value()
        
console.log(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
like image 133
Nina Scholz Avatar answered Sep 18 '22 02:09

Nina Scholz


JavaScript does not guarantee the order of keys in an object, this is why lodash returns you an array, because an object with ordered keys is not guaranteed. See this SO question.

However you can use a Map, which does guarantee the order of the keys.

You can do this with pure JavaScript:

const unsorted = { a: 15, b: 1,c: 2, d: 4, e: 3, f: 6, g: 1 };

const sorted = new Map(Object.entries(unsorted).sort((a, b) => a[1] - b[1]));

for (const [key, val] of sorted) {
  console.log(key, val);
}

You have multiple ways to iterate over the content of the resulting map:

  • map.values(): get the array of values
  • map.entries(): get an array of [key, value] pairs
  • map.keys(): get an array of keys

See the doc about Map.

like image 32
jo_va Avatar answered Sep 18 '22 02:09

jo_va