2

Rookie Javascript question here: I have an object containing arrays like so

const obj = {
  'red': [ 'a', 'b', 'c'],
  'blue': [ 'a' ],
  'green': [ 'a', 'b', 'c', 'd', 'e' ]
}

I want to sort my object so that the properties with the largest arrays come first

obj = {
  'green': [ 'a', 'b', 'c', 'd', 'e' ],
  'red': [ 'a', 'b', 'c'],
  'blue': [ 'a' ]
}

Is there a simple one-liner or lodash method I can achieve this with?

Dhaval Marthak
  • 16,632
  • 6
  • 39
  • 66
Kurai Bankusu
  • 3,821
  • 11
  • 56
  • 114
  • To check whether the "lodash" library have a tool that can do that for you - you can probably review its documentation here: https://lodash.com/docs/ . I'm guessing that there isn't as this is a really uncommon request, mostly as the concept of "ordering properties" is not very well understood and its use cases are quite limited (https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key not withstanding) – Guss Apr 15 '20 at 18:25

2 Answers2

2

Convert your object into an array. Sort the array according to your needs then re-build an object from that array as below :

const obj = {
  'red': ['a', 'b', 'c'],
  'blue': ['a'],
  'green': ['a', 'b', 'c', 'd', 'e']
};

const ordered = {};
const asArray = Object.keys(obj).map(key => ({
  key,
  arr: obj[key]
})); // create an array from the object


asArray.sort((a, b) => b.arr.length - a.arr.length); // sor the array so the array has bigger length should come first

asArray.forEach(r => {
  ordered[r.key] = r.arr
}); // re construct as new object
console.log(ordered);
Eldar
  • 6,531
  • 2
  • 5
  • 25
1

First sort then assign

const obj = {
  'red': [ 'a', 'b', 'c'],
  'blue': [ 'a' ],
  'green': [ 'a', 'b', 'c', 'd', 'e' ]
};

const newObj = {};

let sorted = Object.keys(obj)
    .sort((a, b) => obj[b].length - obj[a].length).forEach(e => newObj[e] = obj[e]);
    
console.log(newObj);
Mohammad Ali Rony
  • 3,431
  • 2
  • 15
  • 27