Home > database >  Sort an Object by the Character length of the Key
Sort an Object by the Character length of the Key

Time:04-09

i have a huge object and try to sort it by the char length of a key.

{
  'cursor-default': 'nbkc',
  'cursor-not-allowed': 'nbjc',
  'cursor-point': 'nblc',
}

shout be

{
  'cursor-not-allowed': 'nbjc',
  'cursor-default': 'nbkc',
  'cursor-point': 'nblc',
}

any hints would be awesome

got it:

var z = Object.keys(names).sort((a, b) => a.length - b.length);

CodePudding user response:

You can get the keys of an object with Object.keys, use a sort with a function that compares the length of the keys, then build a new object using this array.

let temp = {
  key_medium : 'original_pos_1',
  key_short : 'original_pos_2',
  key_loooong : 'original_pos_3',
};

console.log(temp);

let sortedTemp = {};
Object.keys(temp).sort((a,b)=>{
  return b.length - a.length;
}).forEach((key)=>{
  sortedTemp[key] = temp[key];
});

console.log(sortedTemp);

If you wish to change the order, just flip the b.length - a.length to a.length - b.length.

CodePudding user response:

You need to break-down your problem

  1. You need to get keys of your object via Object.keys()
  2. Then you can sort an array of keys
  3. Create a new object by iterating over the sorted keys
const elements = {
  'cursor-default': 'nbkc',
  'cursor-not-allowed': 'nbjc',
  'cursor-point': 'nblc',
}

const sortedKeys = Object
  .keys(elements) // Get ALL keys of the 'elements' object
  .sort((a, b) =>  b.length - a.length)

console.log(sortedKeys); // ['cursor-not-allowed', 'cursor-default', 'cursor-point']

const sorted = {};
for (let key of sortedKeys) {
  sorted[key] = elements[key];
}

console.log(sorted); // {cursor-not-allowed: 'nbjc', cursor-default: 'nbkc', cursor-point: 'nblc'}

Instead of for (... in ...) you can use forEach method of the array:

const sorted = {};
sortedKeys.forEach(key => sorted[key] = elements[key])

Shorter version can be then:

const elements = {
  'cursor-default': 'nbkc',
  'cursor-not-allowed': 'nbjc',
  'cursor-point': 'nblc',
}

const sorted = {};

const sortedKeys = Object
  .keys(elements) // Get ALL keys of the 'elements' object
  .sort((a, b) => b.length - a.length)
  .forEach(key => sorted[key] = elements[key])

console.log(sorted); // {cursor-not-allowed: 'nbjc', cursor-default: 'nbkc', cursor-point: 'nblc'}

EDIT:

If you need to change the order, you can swap the variables in the sort function during the subtraction.

  • Related