skip to Main Content

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


  1. You can use a comparator that calls String#localeCompare on the keys to determine the sorting order when the values are equal.

    const object1 = {
      'Andy': 10,
      "loves": 10,
      "to": 0,
      "Have": 2,
      "tacos": 15,
      "when": 10,
      "he": 0,
      "is": 7,
      "sad": 4
    };
    const res = Object.keys(object1).sort((k1, k2) => 
                  object1[k1] - object1[k2] || k1.localeCompare(k2));
    console.log(res);
    Login or Signup to reply.
  2. You can use Object.entries() and Array#map() as follows:

    const 
        input = { "Andy": 10, "loves": 10, "to": 0, "Have": 2, "tacos": 15, "when": 10, "he": 0, "is": 7, "sad": 4 },
    
        output = Object.entries(input).sort(
            ([k1,v1], [k2,v2]) => v1 - v2 || k1.localeCompare(k2)
        )
        .map(([k,v]) => k);
        
    console.log(output);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search