What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
'abba' & 'baab' == true
'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('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
function anagrams(word, words) {
let result = [];
for (i=0;i<words.length;i++) {
if(check(word,words[i])) {
result.push(words[i]);
}
}
return result;
}
function check(a, b) {
const aArray = a.split('');
const bArray = b.split('');
console.log(aArray.sort().join(''));
console.log(bArray.sort().join(''));
return (aArray.sort().join('') == bArray.sort().join(''));
}
String.prototype.sort = function() {
return this.split("").sort().join("");
};
function anagrams(word, words) {
return words.filter(function(x) {
return x.sort() === word.sort();
});
}
내가 if 문이 참일때만 해당 요소를 push하는 코드를 filter 메서드로 더 간단히 표현하였다.
그 외의 차이점은 없다.