Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!