Naren
Naren

Reputation: 4480

Javascript: Sorting Objects (not arrays) in descending

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
}, {})

Upvotes: 1

Views: 2885

Answers (2)

zer00ne
zer00ne

Reputation: 44086

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()

Upvotes: 1

Cyberboy1551
Cyberboy1551

Reputation: 343

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];
 });

Upvotes: 1

Related Questions