0

If I have the object,

const obj = { Peter: 3, Jeremy: 2, Chris: 1, Adam: 2 };

I want to compare object values, and sort them in a numerical order.

Therefore, I tried

let answer = Object.keys(obj);

answer.sort((a,b) => {
  return obj[b] - obj[a];
})

The output is ['Peter', 'Jeremy', 'Adam', 'Chris'].

I want to sort Jeremy and Adam in Alphabetical order as they have same values.

The output I want is ['Peter', 'Adam', 'Jeremy', 'Chris']

How do I approach to this answer?

Aden Lee
  • 230
  • 2
  • 15
  • 1
    `if (values are the same) { } else { }` -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Jan 09 '23 at 13:02
  • This is essentially the logic you're after [How can I sort a javascript array of objects numerically and then alphabetically?](https://stackoverflow.com/a/12900176) so `(a,b) => obj[b] - obj[a] || a.localeCompare(b)` would be your compare function. – Nick Parsons Jan 09 '23 at 13:08

2 Answers2

2

you can use a condition for case where values are same to sort based on alphabetical order of keys

const obj = { Peter: 3, Jeremy: 2, Chris: 1, Adam: 2 };

let answer = Object.keys(obj);

answer.sort((a,b) => {
    if (obj[b] == obj[a]) return a.localeCompare(b)
    return obj[b] - obj[a];
})

console.log(answer)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

ashish singh
  • 6,526
  • 2
  • 15
  • 35
1

const obj = { Peter: 3, Jeremy: 2, Chris: 1, Adam: 2 };

const result = Object.entries(obj) // get array of [key, value]
  // sort by value descending, then alphabetically by key
  .sort(([a,b],[c,d])=>d-b || a.localeCompare(c)) 
  .map(([i])=>i) // extract just the key

console.log(result)
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27