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

130
Visualizações
Convert array of strings to hashmap with count javascript

Is there a better way to convert

["88 99", "20 99", "12 12"]

to a hashmap in the form

{"88": 1, "99": 2, "20": 1, "12": 1}

Using map or reduce?

Where in this case, a string with duplicate numbers only gets increases it's count by 1.

Currently I'm converting the above array into a 2d array using .split(' ') and iterating over that 2d array in another for loop as so:

var counts = {}
    for (let i = 0; i < logs.length; i++){
      let ack = logs[i].split(' ');
      if(ack[0]==ack[1]){
        counts[ack[0]] = counts[ack[0]] ? counts[ack[0]] + 1 : 1; 
      }
      else{
      for(let j= 0; j < 2; j++){
         counts[ack[j]] = counts[ack[j]] ? counts[ack[j]] + 1 : 1;  
                               }
          }
      
     }

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

First I group by numbers, summing the appearances of each. This is using the reduce part. That's it. I used adaption of method by https://stackoverflow.com/a/62031473/3807365

var arr = ["88 99", "20 99", "12 12"]

var step1 = arr.reduce(function(agg, pair) {
  pair.split(" ").forEach(function(item) {
    agg[item] = (agg[item] || 0) + 1
  })
  return agg;
}, {})

console.log(step1)

about 4 years ago · Santiago Gelvez Relatório

0

Yes. I'm assuming you want to write in a functional style, so I'm not worrying about efficiency, etc.

You can collapse this into a hairy one-liner but I wrote the intermediate steps and output them for illustration.

const input = ["88 99", "20 99", "12 12"];

const split = input.map( (string) => string.split(" ") );
console.log("split: " + JSON.stringify(split));

const flattened = split.reduce( (acc,array) => acc = acc.concat(array), []);
console.log("flattened: " + JSON.stringify(flattened));

const output = flattened.reduce( (byKey, item) => {
    if (!byKey[item]) byKey[item] = 0;
    byKey[item]++;
    return byKey;
}, {});
console.log(JSON.stringify(output))

about 4 years ago · Santiago Gelvez 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