Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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': [],
}
like image 395
Dawn17 Avatar asked Oct 29 '25 04:10

Dawn17


2 Answers

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);
like image 155
Aleks Avatar answered Oct 30 '25 19:10

Aleks


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.

like image 21
gurisko Avatar answered Oct 30 '25 18:10

gurisko