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

128
Visualizações
Finding anagrams of a word in an array

PROBLEM: Two words are anagrams of each other if they both contain the same letters. For example:


'abba' & 'bbaa' == true

'abba' & 'abbba' == false

'abba' & 'abca' == false

Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:


anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']

anagrams('laser', ['lazing', 'lazy',  'lacer']) => []

MY SOLUTION:

function anagrams(word, words){
  let array = [];
  let answer = [];
  for(i in words){
    array.push(words[i].split('').sort().join(''));
  }
  for(i in array){
    if(word == array[i]){
      answer.push(words[i]);
    }
   return answer;
  }
}

However, this just return an empty array. What is wrong with my code ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Sort your word, match each sorted(item) in words array with your sorted word, push to the final array, and return, I have separated sorting in a diff function for better understanding

function clean(str) {
  return str.replace(/[^\w]/g).toLowerCase().split('').sort().join();
}

function anagrams(word, words) {
  let answer = [];
  for (i in words) {
    if (clean(word) == clean(words[i]))
      answer.push(words[i]);
  }
  return answer;
}

console.log(anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']));

console.log(anagrams('laser', ['lazing', 'lazy',  'lacer']));

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