Skip to content

Instantly share code, notes, and snippets.

@yakovenkodenis
Last active January 3, 2017 17:06
Show Gist options
  • Save yakovenkodenis/5815df4cbe3b5350abd4193156213513 to your computer and use it in GitHub Desktop.
Save yakovenkodenis/5815df4cbe3b5350abd4193156213513 to your computer and use it in GitHub Desktop.
A function that takes an array of random words and outputs a two-dimensional array of anagrams.
// Very inefficient but purely declarative approach
const findAnagrams = words => {
const pairIsAnagram = (word1, word2) =>
word1.split('').sort()
.reduce(
(acc, el, i) => { acc[i] = el == acc[i]; return acc; },
word2.split('').sort()
)
.reduce((acc, el, i) => acc && el, true);
return words.map(
word1 => words.reduce(
(acc, word2, i) => word2 !== word1 && pairIsAnagram(word1, word2) ? [...acc, [word1, word2]] : [...acc], []
)
).filter(el => el.length > 0)
.map(el => el[0].sort())
.reduce((acc, el) => acc.map(e => e.toString()).indexOf(el.toString()) < 0 ? [...acc, el] : [...acc], []);
};
const words = ['стол', 'барокко', 'слот', 'кот', 'кошка', 'ток', 'коробка'];
console.log(findAnagrams(words));
// [
// ['стол', 'слот'],
// ['кот', 'ток'],
// ['барокко', 'коробка'],
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment