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

169
Vistas
Sorting map by key returns sorted Map object with the first key in last index

The following function creates a Map object from two arrays. I am trying to sort the map by key into a new Map object by using the sort method, as shown on Mozilla Docs. The mapSort object is correctly sorting all of the keys, besides the fact that it is putting the first key at the last index.

const sortMapByKey = () => {
  const keyArray = [4, 6, 16, 18, 2]
  const valueArray = [103, 123, 4444, 99, 2000]

  const buildMap = (keys, values) => {
      const map = new Map();
      for(let i = 0; i < keys.length; i++){
        map.set(keys[i], values[i]);
      };
      const mapSort = new Map([...map.entries()].sort(function(a, b) {
        return a - b;
      }));
      return mapSort
    };  
    
    return buildMap(keyArray, valueArray)
}

The current output:

Map { 4 => '103', 6 => '123', 16 => '4444', 18 => '99', 2 => '2000' }

The desired output:

Map {  2 => '2000', 4 => '103', 6 => '123', 16 => '4444', 18 => '99' }

Any clue on what I'm doing wrong with my sort?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The entries are a key-value pair, eg [1, 103]. Doing return a - b tries to subtract two such arrays from each other, which doesn't make sense - you need to extract the key from the entry pair first.

const mapSort = new Map([...map.entries()].sort(function(entryA, entryB) {
  return entryA[0] - entryB[0];
}));

const keyArray = [4, 6, 16, 18, 2]
const valueArray = [103, 123, 4444, 2000]

const buildMap = (keys, values) => {
  const map = new Map();
  let objectArray = []
  for (let i = 0; i < keys.length; i++) {
    map.set(keys[i], values[i]);
  };
  const mapSort = new Map([...map.entries()].sort(function(entryA, entryB) {
    return entryA[0] - entryB[0];
  }));
  return mapSort
};

console.log(buildMap(keyArray, valueArray));

or destructure:

const mapSort = new Map(
  [...map.entries()]
    .sort(([a], [b]) => a - b)
);

const keyArray = [4, 6, 16, 18, 2]
const valueArray = [103, 123, 4444, 2000]

const buildMap = (keys, values) => {
  const map = new Map();
  let objectArray = []
  for (let i = 0; i < keys.length; i++) {
    map.set(keys[i], values[i]);
  };
  const mapSort = new Map(
    [...map.entries()]
      .sort(([a], [b]) => a - b)
  );
  return mapSort
};

console.log(buildMap(keyArray, valueArray));

about 4 years ago · Juan Pablo Isaza 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