Javascript Coding Exercise – Anagrams


Check to see if two provided strings are anagrams of each other. One string is an anagram of another if it uses the same characters in the same quantity.

  • Only consider characters, not spaces or punctuation
  • Consider capital letters to be the same as lower case

Examples:

anagrams('rail safety', 'fairy tales') === true
anagrams('RAIL! SAFETY!', 'fairy tales') === true
anagrams('Hi there', 'Bye there') === false

To check if two strings are anagrams of each other, you can break down the problem into the following steps:

  1. Remove spaces and punctuation from the strings.
  2. Convert the strings to lowercase to handle case insensitivity.
  3. Compare the frequency of characters in both strings.

Here’s a possible solution:

function anagrams(stringA, stringB) {
  // Helper function to clean and sort string
  const cleanString = (str) => {
    return str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
  };

  // Compare cleaned and sorted strings
  return cleanString(stringA) === cleanString(stringB);
}

// Test cases
console.log(anagrams('rail safety', 'fairy tales'));  // true
console.log(anagrams('RAIL! SAFETY!', 'fairy tales'));  // true
console.log(anagrams('Hi there', 'Bye there'));  // false

Explanation:

The cleanString function:

  • Removes non-alphanumeric characters using replace(/[^\w]/g, '').
  • Converts the string to lowercase.
  • Splits the string into an array of characters, sorts them, and joins them back into a string.

The main function compares the cleaned and sorted versions of both strings. If they are equal, the strings are anagrams.

Leave a Reply

Your email address will not be published. Required fields are marked *