Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort by values but alphabetical order when values are same in Javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading