-
Notifications
You must be signed in to change notification settings - Fork 0
/
08-where-my-anagragms-at.js
32 lines (30 loc) · 1.22 KB
/
08-where-my-anagragms-at.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* 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
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']) => [] */
// #1 (imperative)
export const anagrams = (word, words) => {
const sortAlphabets = text => `${text}`.split('').sort().join('');
const sortedWord = sortAlphabets(word);
let result = [];
for (let i = 0; i < words.length; i += 1) {
const sortedOneOfWords = sortAlphabets(words[i]);
if (sortedWord === sortedOneOfWords) {
result = result.concat(words[i]);
}
}
return result;
};
// solution #2 (functional)
export const anagrams2 = (word, words) => {
const stringSort = text => `${text}`.split('').sort().join('');
return words.filter(n => stringSort(n) === stringSort(word));
};