Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
How can I sort keys and values in Map in Javascript

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?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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]);

about 4 years ago · Santiago Gelvez Report

0

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")

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!