Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda