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

195
Visualizações
Condensing code that compares whether one string can be arranged to create another string

The challenge to solve was to write a function that takes two strings as inputs and if the first string can be re-arranged to create the second string, return the string "true". If not, return "false". I was able to solve it, but my solution is beefy and not exactly eloquent. I would like tips/tricks for condensing the code that I wrote.

//to solve, create (2) objects with the values as the # of appearances of chars
// in the (2) strings
const countStr1 = {};
const countStr2 = {};
for(let chr of str1) {
  if (countStr1[chr]) {
    countStr1[chr]++;
  } else{
    countStr1[chr] = 1;
  }
}
for(let chr2 of str2){
  if(countStr2[chr2]){
    countStr2[chr2]++;
  } else{
    countStr2[chr2] = 1;
  }
}
//  console.log(countStr1);
//  console.log(countStr2);
// create (2) arrays of keys:
const keys1 = Object.keys(countStr1);
const keys2 = Object.keys(countStr2);
//console.log(keys1.length);
//console.log(keys2.length);
  
if (keys2.length > keys1.length){
  return "false";
}

  for (let key of keys2) {
//  console.log(countStr1[key]);
  if (countStr1[key] < countStr2[key]){
    return "false";
  }
return "true";
}  
}
   
// keep this function call here 
console.log(StringScramble("cdoer","coder"));```

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