Skip to content

Latest commit

 

History

History
47 lines (32 loc) · 1.25 KB

where-my-anagrams-at.md

File metadata and controls

47 lines (32 loc) · 1.25 KB

Where my anagrams at? 5 Kyu

LINK TO THE KATA - STRINGS ALGORITHMS

Description

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']) => []

Solution

const getWordSortedAlphabetically = string => {
  return string.split('').sort().join('')
}

const anagrams = (word, words) => {
  const wordSortedAlphabetically = getWordSortedAlphabetically(word)

  return words.filter(word => {
    return wordSortedAlphabetically === getWordSortedAlphabetically(word)
  })
}