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

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.