-1

Suppose i have an object obj1= {key1:[1,2,3],key2:[333,11],key3:[9938,33,0,39,2]} How to sort this by length of value array. I tried using Lodash method but that didnt worked. Required output

obj1= {key3:[9938,33,0,39,2],key1:[1,2,3],key2:[333,11]}

Rrptm
  • 329
  • 2
  • 12
  • 1
    Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – Vla Mai Mar 18 '21 at 05:26
  • Does this answer your question? [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – codemonkey Mar 18 '21 at 05:32

2 Answers2

1

First a disclaimer: JavaScript objects are typically considered to be unordered key/value pairs. While recent versions of the ECMAScript specification do stipulate how object properties are ordered, the rules are complex, and it remains good advice to not rely on object order unless you know what you're doing.

That being said, you can use Object.entries() and Object.fromEntries() to get your desired result:

const o = {
  key1: [1,2,3],
  key2: [333,11], 
  key3: [9938,33,0,39,2]
};

const r = Object.fromEntries(
  Object.entries(o).sort(([k1, v1], [k2, v2]) => v2.length - v1.length)
);

console.log(r);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
-1

test it

let obj2={}
        let obj1= {key3:[9938,33,0,39,2],key1:[1,2,3],key2:[333,11]}
        Object.keys(obj1)
        .sort((a,b)=>{
            if (obj1[a].length>obj1[b].length) {
                return -1
            }
            if (obj1[a].length<obj1[b].length) {
                return 1
            }
            return 0
        })
        .map(x=>{
            obj2[x]=obj1[x]
        })
        console.log(obj2);