Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

324
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda