0

I have an Object like this:

object = {A: 15, B: 30, C: 22}

So I'm sorting it using its values. For that, I have this function:

object = {
  A: 15,
  B: 30,
  C: 22
}
function sortObjsValues(obj) {
  return Object.values(obj).sort((a, b) => {
    if (a > b) {
      return -1;
    } else if (a < b) {
      return 1;
    } else {
      return 0;
    }
  });
}

console.log(sortObjsValues(object)); // => returns 30,22,15

Is there a way to return its keys instead of its values, keeping sorting by its values? The final result would be B,C,A

2 Answers 2

4

You could get entries from the object, sort by value descending and map the keys.

const
    object = { A: 15, B: 30, C: 22 },
    getSortedKeys = o => Object
        .entries(o)
        .sort((a, b) => b[1] - a[1])
        .map(([k]) => k);

console.log(getSortedKeys(object));

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

Comments

2

Just sort the keys by the value.

const object = { A: 15, B: 30, C: 22 };

console.log(Object.keys(object).sort((a, b) => object[b] - object[a]));

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.