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

329
Vistas
How to iterate through map and push keys with similar values into the same array?

I've got javascript map with structure like this:

let map = {3 => 1,
           15 => 2,
           0 => 2,
           8 => 3,
           9 => 3}

I need to receive the arrays of keys, and keys with similar values should be in the same array.

[[3], [15,0],[8,9]]

This is what I've tried:

    let answers = [];
    let currentVal = 1;
    map.forEach((value, key)=>{
      let subArr = [];
      if(value === currentVal){
        subArr.push(key);
        answers.push(subArr);
        currentVal++;
   }

    });
    
    return answers;

And it returns [[3], [15], [8]]

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

0

I assume your map is an object, not map for readability reasons, but if u are using Map there you can change methods to get elements but main idea you can see below:

const data = {
  3: 1,
  15: 2,
  0: 2,
  8: 3,
  9: 3
};

const customData = Object.entries(data).reduce((acc, [key, value]) => {
  if (value in acc) {
    acc[value].push(key);
  } else {
    acc[value] = [key];
  }

  return acc;
}, {});

const finalArray = Object.values(customData);
console.log(finalArray);

Edit with Map() example:

const data = new Map([
  [3, 1],
  [15, 2],
  [0, 2],
  [8, 3],
  [9, 3]
]);

const customData = Array.from(data).reduce((acc, [key, value]) => {
  if (value in acc) {
    acc[value].push(key);
  } else {
    acc[value] = [key];
  }

  return acc;
}, {});

const finalArray = Object.values(customData);
console.log(finalArray);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use Object.entries and destructuring key, value but I change their place as value, key to match the data structure map provided by OP :

let map = { 3: 1, 15: 2, 0: 2, 8: 3, 9: 3 };
const arr = [];
for (const [value, key] of Object.entries(map)) {
  if (arr[key]) {
    arr[key].push(value);
  } else {
    arr[key] = [value];
  }
}
console.log(arr.filter(Boolean)); // [[3], [15,0],[8,9]]

NOTE arr.filter(Boolean) to remove falsy (empty) values from array since index 0 have no array inside of it!

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