1

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
10
  • 4
    Object properties don't have a guaranteed order, like array elements do. Commented Jul 11, 2019 at 20:23
  • 1
    Maybe sort them first: Object.keys(x).sort((a, b) => b.localeCompare(a)).reduce() Commented Jul 11, 2019 at 20:25
  • 2
    You can't reliably sort something that doesn't have a guaranteed order. Use arrays if you need them sorted! Commented Jul 11, 2019 at 20:27
  • 1
    @James—since ECMAScript 2017 they do, see the abstract operation OrdinaryOwnPropertyKeys which is used by various methods when accessing property names. However not all implementations in use may be compliant. Commented Jul 11, 2019 at 20:33
  • 2
    @James That is no longer true. Javascript objects do have guaranteed order, assuming your key names aren't positive integer values. I would never recommend using an object for anything reliant on order, but the notion that "object properties don't have a guaranteed order" is misinformation. Commented Jul 11, 2019 at 20:44

2 Answers 2

1

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
1
  • See the comment on zer00ne's answer above. Commented Jul 12, 2019 at 1:18
1

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
2
  • 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. Commented Jul 12, 2019 at 1:13
  • I thought Object.entries() returns [[key, value], [ley, value],...] in this case key turns into a string. And Map() accepts anything as a key in insertion order. Oh, the .sort() is useless then? Will update. Commented Jul 13, 2019 at 1:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.