I have an object of key (str): value (arr) pair.
const obj = {
   '1': []
   '2': ['a', 'b'],
   '3': [],
   '4': ['c']
}
I would like to sort this by the number of elements that each key has in the value.
So that it would be like,
const obj = {
   '2': ['a', 'b'],
   '4': ['c']
   '1': []
   '3': [],
}
After some searching, I tried this syntax
const sortable = Object.fromEntries(
    Object.entries(obj).sort(([,a],[,b]) => b.length)
);
But this gives me undefined.
Any help?
EDIT
Sorry the keys are String
More detailed example
const obj = {
    '1.2.3': [1,2,3,4],
    'ABC12': [],
    'CAA11': [3,5],
    '4.4.1': [1,2,3],
}
to
const obj = {
    '1.2.3': [1,2,3,4],
    '4.4.1': [1,2,3],
    'CAA11': [3,5],
    'ABC12': [],
}
Assuming that all keys are integers
Object.keys(obj).sort((a,b)=>a-b).reduce((acc, key)=>((acc[key]=obj[key]), acc),{});
Returns new object with sorted keys
Edit: Sorted based on value length (array length);
Object.keys(obj).sort((a,b)=>obj[b].length - obj[a].length)
    .reduce((acc, key)=>((acc[key]=obj[key]), acc),{});
const obj = {
    '1.2.3': [1,2,3,4],
    'ABC12': [],
    'CAA11': [3,5],
    '4.4.1': [1,2,3],
}
const res = Object.keys(obj)
                  .sort((a,b)=>obj[b].length - obj[a].length)
                  .reduce((acc, key)=>((acc[key]=obj[key]), acc),{});
console.log(res);What you are looking for is most probably:
Object.entries(obj).sort(([, a], [, b]) => b.length - a.length);
However, the output of the code above is an array consisting of enumerable property [key, value] pairs of the object again. Sorting the object's keys inside of the object itself can't be achieved.
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