0
    function anagrams(word, words) {
       var returnArray = [];
       var wordToTest= word.split("").sort();
       for(i=0; i<=words.length; i++){
          var wordssToTest = words[i].split("");
          wordssToTest.sort();
          if(wordssToTest==wordToTest){
             returnArray.push(wordssToTest);
          }
       }
     return returnArray;


    }

Hello! I need to create a function, where the input is a string (word) and an array of strings (words). My objective is to return a new array, which will contain a list of all the words in the 'words' string that are anagrams to the 'word' string.

I wrote the code, yet it doesn't recognize the words[i].split("") function on the 5th line, says it's an unknown property of undefined..
Any help?

2 Answers 2

1

You used <= instead of < in the for loop. Correct code:

function anagrams(word, words) {
       var returnArray = [];
       var wordToTest= word.split("").sort();
       for(i=0; i<words.length; i++){
          var wordssToTest = words[i].split("");
          wordssToTest.sort();
          if(wordssToTest==wordToTest){
             returnArray.push(wordssToTest);
          }
       }
     return returnArray;


    }
Sign up to request clarification or add additional context in comments.

Comments

0

Here is a much more simpler solution using Array#filter method:

function anagrams(word, words) {
  return words.filter(el =>
    word.split('').sort().toString() === el.split('').sort().toString()
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.