I have a situation where I want to create an array based on values (numbers) in an object like so. However, the catch is that if there is ever multiple keys with the same value, then I want the secondary rule to be to sort the array based on alphabetical order. For example:
const object1 = {
'Andy': 10,
"loves": 10,
"to": 0,
"Have": 2,
"tacos": 15,
"when": 10,
"he": 0,
"is": 7,
"sad": 4
};
const result = []
//Expected Result: ["he", "to", , "Have", "sad", "is", 'Andy', "loves", "when":, "tacos"]
So in this case there are multiple values with 0, but "he" would come before "to" in the array because of the secondary rule of prioriting alphabetical order.
I know that I should be able to convert the object into an array and then sort it based on value, but I cant figure out how to enact the secondary alphabetical rule. Can anyone guide me as to what might be the most optimal way to accomplish this?
2
Answers
You can use a comparator that calls
String#localeCompare
on the keys to determine the sorting order when the values are equal.You can use
Object.entries()
andArray#map()
as follows: