Home > database >  How can I sort keys and values in Map in Javascript
How can I sort keys and values in Map in Javascript

Time:07-17

I am trying to get the key that has maximum value in the map which I have created through new Map() and added the keys & values in it.

Now, I wanted to get the key whose value is maximum and if two keys have the same values then I want to return the lexicographically largest.

For eg: {'a': 20, 'b':20} then I want b to be return.

my code:

var slowestKey = function(releaseTimes, keysPressed) {
    let map=new Map();
     map.set(keysPressed[0],releaseTimes[0]);  
    for(let i=0; i<releaseTimes.length-1; i  ){
         let time=releaseTimes[i 1]-releaseTimes[i];
            map.set(keysPressed[i 1],time);
    }
    let max= Math.max(...map.values());
    console.log(map)
    console.log(Math.max(...map.values()));
    
};

Input:

Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"

Expected Output: "c"

console.log:

Map(3) { 'c' => 20, 'b' => 20, 'd' => 1 }
20

How can I get the key whose value is maximum and lexicographically bigger?

CodePudding user response:

With filter you can filter the keys whose value = max value, then you can sort, and get the first item.

So, the extra code will be

const [key] = [...map.keys()].filter(key => {
      return map.get(key) === max
 }).sort((a, b) => a - b)

var slowestKey = function(releaseTimes, keysPressed) {
    let map=new Map();
     map.set(keysPressed[0],releaseTimes[0]);  
    for(let i=0; i<releaseTimes.length-1; i  ){
         let time=releaseTimes[i 1]-releaseTimes[i];
            map.set(keysPressed[i 1],time);
    }
    let max= Math.max(...map.values());
    const [key] = [...map.keys()].filter(key => {
      return map.get(key) === max
    }).sort((a, b) => a - b)
    console.log(key)
};


slowestKey([9,29,49,50], "cbcd")

CodePudding user response:

By having an array of key/value pairs, you could sort by

  • value descending
  • key descending

and take the first pair (index 0).

const
    pairs = [['c', 9], ['b', 29], ['c', 49], ['d', 50], ['a', 50]];

pairs.sort((a, b) => b[1] - a[1] || b[0].localeCompare(a[0]));

console.log(pairs[0]);

  • Related