How to sort an object based on its value's length

Viewed 379

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': [],
}
3 Answers

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.

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

let obj = {
   '1.2.3': [1,2,3,4],
  'ABC12': [],
  'CAA11': [3,5],
  '4.4.1': [1,2,3],
}
console.log(obj);
let entries = Object.entries(obj).sort((a,b) => { return b[1].length - a[1].length;});
let tempObj = {};
for(let i = 0; i < entries.length; i++){
  tempObj[entries[i][0]] = entries[i][1]; 
}
obj = tempObj;
console.log(obj);

Related