How to Create an Anagram Checker in JavaScript?

Estimated read time 2 min read

To create an anagram checker in JavaScript, you can compare two input words or phrases to see if they are anagrams of each other. One approach is to convert the input words or phrases to arrays of characters, sort the arrays alphabetically, and then compare the sorted arrays to see if they are equal. Here’s an example code snippet that demonstrates how to create an anagram checker in JavaScript:

function isAnagram(word1, word2) {
  // Convert the words to arrays of characters
  const characters1 = word1.toLowerCase().split("");
  const characters2 = word2.toLowerCase().split("");

  // Sort the arrays alphabetically
  const sorted1 = characters1.sort().join("");
  const sorted2 = characters2.sort().join("");
  
  // Compare the sorted arrays
  return sorted1 === sorted2;
}

console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("hello", "world")); // false

In this code, the isAnagram() function takes two arguments: word1 and word2 which represent the two input words or phrases.

Inside the function, the input words are first converted to arrays of characters using the split() method and converted to lowercase using the toLowerCase() method.

The sort() method is then used to sort the arrays alphabetically, and the join() method is used to join the sorted characters back into strings.

Finally, the two sorted strings are compared using the === operator to see if they are equal, and the result of the comparison is returned from the function.

The console.log() statements at the end of the code demonstrate how to use the isAnagram() function to check if two input words are anagrams of each other. You can replace “listen” and “silent” with any other words or phrases to test the function with different inputs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply