'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 ?
Solution 1:[1]
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']));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tushar |