I know objects are by default sorted out in ascending order or the way we will insert but I need the best way to sort the object in descending order. Ex:
Input x = {
a: {},
b: {},
c: {},
d: {}
}
Output: x = {
d: {},
c: {},
b: {},
a: {}
}
I tried the below solution, It works but is it a good practice or can I get anything better on this?
x= Object.keys(x).sort().reverse().reduce((obj, key) => {
obj[key] = x[key]
return obj
}, {})
asked Jul 11, 2019 at 20:22
2 Answers 2
You can use the Array.sort method. I believe this will only sort on the first level depth
const list =
{
a: "4",
c: "2",
b: "3",
d: "1"
}
const sortedList = {};
Object.keys(list).sort().reverse().forEach(function(key) {
sortedList[key] = list[key];
});
answered Jul 11, 2019 at 20:42
-
See the comment on zer00ne's answer above.RobG– RobG2019年07月12日 01:18:21 +00:00Commented Jul 12, 2019 at 1:18
Use a Map to guarantee order while using Object.entries()
method to preserve key/value pairs.
- Get an array of arrays from
Object.entries()
.reverse()
it- Convert it into a Map (
Map()
guarantees order according to how it was entered) - Use Object.fromEntries() on Map to return an object.
let obj = {a:{}, b:{}, c:{}, d:{}};
let rev = new Map(Object.entries(obj).reverse());
let ent = Object.fromEntries(rev);
console.log(ent);
See compatibility table for Object.fromEntries()
answered Jul 11, 2019 at 21:01
-
You can't enforce a particular sorting in general. Since ECMAScript 2017, the order is positive integer keys in ascending numeric order, then strings that aren't symbols in insertion order, then symbols in insertion order. So you can't order integer keys in descending order and can't mix integers, strings and symbols. The abstract operation OrdinaryOwnPropertyKeys is used by everything that gets keys.RobG– RobG2019年07月12日 01:13:24 +00:00Commented Jul 12, 2019 at 1:13
-
I thought
Object.entries()
returns[[key, value], [ley, value],...]
in this case key turns into a string. AndMap()
accepts anything as a key in insertion order. Oh, the.sort()
is useless then? Will update.zer00ne– zer00ne2019年07月13日 01:56:25 +00:00Commented Jul 13, 2019 at 1:56
lang-js
Object.keys(x).sort((a, b) => b.localeCompare(a)).reduce()