How to Create an Anagram Function in JavaScript?

Estimated read time 2 min read

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. To create an anagram function in JavaScript, you can take a word or phrase as input, convert it to an array of characters, shuffle the array randomly, and then join the characters back into a string. Here’s an example code snippet that demonstrates how to create an anagram function in JavaScript:

function createAnagram(word) {
  // Convert the word to an array of characters
  const characters = word.split("");

  // Shuffle the characters randomly
  for (let i = characters.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [characters[i], characters[j]] = [characters[j], characters[i]];
  }

  // Join the shuffled characters back into a string
  const anagram = characters.join("");
  
  // Return the resulting anagram
  return anagram;
}

console.log(createAnagram("hello")); // "loleh"

In this code, the createAnagram() function takes one argument: word which represents the input word or phrase.

Inside the function, the input word is first converted to an array of characters using the split() method.

The for loop is then used to shuffle the characters in the array randomly using the Fisher-Yates shuffle algorithm.

Finally, the shuffled characters are joined back into a string using the join() method, and the resulting anagram is returned from the function.

The console.log() statement at the end of the code demonstrates how to use the createAnagram() function to create an anagram from the input word “hello”. You can replace “hello” with any other word or phrase to create a different anagram.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply