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]
You could build a new object with the sorted key/value pairs.
The actual standard or the order of properties:
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>
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 valuesmap.entries()
: get an array of [key, value]
pairsmap.keys()
: get an array of keysSee the doc about Map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With