Anagrams
You will receive an array of strings.
Submit that array of strings, sorted from A-Z, but only supply the words that are an anagram of another word in that array.
Example puzzle
[ "kiwi", "melon", "apple", "lemon" ]
Example solution
[ "lemon", "melon" ]
Actual data used in the competition
Explanation
This challenge required you to split words into characters and sort them:
- Write a function that identifies if two words are anagrams – Sort the letters of both words alphabetically – Iterate word 1, and create an object map for each character, counting the occurance of each – Iterate word 2, and check if the character count matches
- Iterate over the array of words
- For each word, iterate over the remaining words in the array
- If the current word is an anagram of the other word, add it to the result array
Code solutions
There are many ways to solve this. This JavaScript solution is nice and short:
let sortobj = {};
let anagrams = [];
puzzle.forEach(function (item) {
let id = item.split('').sort().join('');
if (!sortobj[id]) { sortobj[id] = []; }
sortobj[id].push(item);
});
for (let i in sortobj) {
if (sortobj[i].length > 1) {
sortobj[i].forEach(function (e) {
anagrams.push(e);
});
}
}
anagrams.sort();
Other submissions: