0

How do I sort this array of objects by checking the objects' key?

const list = [
  { "firstValue": { "a": "1" } },
  { "secondValue": { "b": "1" } },
  { "thirdValue": { "c": "1" } },
  { "fourthValue": { "d": "1" } },
  { "fifthValue": { "e": "1" } }
]

So in this case I want it to be sorted like:

const list = [
  { "fifthValue": { "e": "1" } },
  { "firstValue": { "a": "1" } },
  { "fourthValue": { "d": "1" } },
  { "secondValue": { "b": "1" } },
  { "thirdValue": { "c": "1" } }
]

This is my current code:

sortArrOfObjectsByKey(list);
document.write(JSON.stringify(list))

function sortArrOfObjectsByKey(arrToSort) {
    arrToSort.sort(function(a, b) {
       return a < b ? -1 : 1
    });
}

But it doesn't get sorted correctly. Please note that there shouldn't be any new container for the new sorted array/object. Help! Thanks

kzaiwo
  • 1,558
  • 1
  • 16
  • 45

1 Answers1

1

You need to fetch property name and then sort according to that

const list = [
  { "firstValue": { "a": "1" } },
  { "secondValue": { "b": "1" } },
  { "thirdValue": { "c": "1" } },
  { "fourthValue": { "d": "1" } },
  { "fifthValue": { "e": "1" } }
]

list.sort( function(a, b) {
  const aKey = Object.keys(a)[0];
  const bKey = Object.keys(b)[0];
  return aKey.localeCompare(bKey)
} );

console.log(list)
Rajesh
  • 24,354
  • 5
  • 48
  • 79