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?
if (values are the same) { <compare keys> } else { <compare values> }-> How much research effort is expected of Stack Overflow users?(a,b) => obj[b] - obj[a] || a.localeCompare(b)would be your compare function.