Reputation: 1
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?
Upvotes: 0
Views: 465
Reputation: 986
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()
);
}
Upvotes: 0
Reputation: 8287
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;
}
Upvotes: 1