Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript anagram comparison

Tags:

javascript

I'm trying to compare two strings to see if they are anagrams.

My problem is that I'm only comparing the first letter in each string. For example, "Mary" and "Army" will return true but unfortunately so will "Mary" and Arms."

How can I compare each letter of both strings before returning true/false?

Here's a jsbin demo (click the "Console" tab to see the results"):

http://jsbin.com/hasofodi/1/edit

function compare (a, b) {
  y = a.split("").sort();
  z = b.split("").sort();
  for (i=0; i<y.length; i++) {
    if(y.length===z.length) {
      if (y[i]===z[i]){
        console.log(a + " and " + b + " are anagrams!");
        break;
      }
      else {
        console.log(a + " and " + b + " are not anagrams.");
        break;
      }
    }
    else {
      console.log(a + " has a different amount of letters than " + b);
    }
    break;
  }
}

compare("mary", "arms");
like image 433
Ryan Avatar asked May 21 '14 14:05

Ryan


People also ask

How do you compare anagrams?

Two words are anagrams of each other if they contain the same number of characters and the same characters. You should only need to sort the characters in lexicographic order, and determine if all the characters in one string are equal to and in the same order as all of the characters in the other string.


1 Answers

Quick one-liner solution with javascript functions - toLowerCase(), split(), sort() and join():

  • Convert input string to lowercase
  • Make array of the string with split()
  • Sort the array alphabetically
  • Now join the sorted array into a string using join()

Do the above steps to both strings and if after sorting strings are the same then it will be anargam.

// Return true if two strings are anagram else return false

function Compare(str1, str2){
     if (str1.length !== str2.length) {
        return false
     }
  
    return str1.toLowerCase().split("").sort().join("") === str2.toLowerCase().split("").sort().join("")
}

console.log(Compare("Listen", "Silent")) //true
console.log(Compare("Mary", "arms")) //false
like image 116
mk22 Avatar answered Nov 16 '22 00:11

mk22