Skip to content Skip to sidebar Skip to footer

Javascript Anagram Comparison

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 tr

Solution 1:

Instead of comparing letter by letter, after sorting you can join the arrays to strings again, and let the browser do the comparison:

function compare (a, b) {
    var y = a.split("").sort().join(""),
        z = b.split("").sort().join("");
    console.log(z === y
        ? a + " and " + b + " are anagrams!"
        : a + " and " + b + " are not anagrams."
    );
}

Solution 2:

If you want to write a function, without using inbuilt one, Check the below solution.

functionisAnagram(str1, str2) {

  if(str1 === str2) {
    returntrue;
  }

  let srt1Length = str1.length;
  let srt2Length = str2.length;

  if(srt1Length !== srt2Length) {
    returnfalse;
  }

  var counts = {};

  for(let i = 0; i < srt1Length; i++) {
    let index = str1.charCodeAt(i)-97;
    counts[index] = (counts[index] || 0) + 1;
  }

  for(let j = 0; j < srt2Length; j++) {
    let index = str2.charCodeAt(j)-97;
    if (!counts[index]) { 
      returnfalse; 
    }
    counts[index]--;
  }

  returntrue;
}

Solution 3:

This considers case sensitivity and removes white spaces AND ignore all non-alphanumeric characters

functioncompare(a,b) {
    var c = a.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
    var d = b.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
        return (c ===d) ? "Anagram":"Not anagram";
}

Solution 4:

I modified your function to work.

It will loop through each letter of both words UNTIL a letter doesn't match (then it knows that they AREN'T anagrams).

It will only work for words that have the same number of letters and that are perfect anagrams.

functioncompare(a, b) {
  y = a.split("").sort();
  z = b.split("").sort();
  areAnagrams = true;
  for (i=0; i<y.length && areAnagrams; i++) {
    console.log(i);
    if(y.length===z.length) {
      if (y[i]===z[i]){
        // good for now
        console.log('up to now it matches');
      } else {
        // a letter differs
        console.log('a letter differs');
        areAnagrams = false;
      }
    }
    else {
      console.log(a + " has a different amount of letters than " + b);
      areAnagrams = false;
    }

  }
  if (areAnagrams) {
    console.log('They ARE anagrams');
  } else {
    console.log('They are NOT anagrams');
  }
    return areAnagrams;
}

compare("mary", "arms");

Solution 5:

A more modern solution without sorting.

function(s, t) {
 if(s === t) returntrueif(s.length !== t.length) returnfalselet count = {}

 for(let letter of s)
  count[letter] = (count[letter] || 0) + 1for(let letter of t) { 
  if(!count[letter]) returnfalseelse --count[letter]
 }

 returntrue;
}

Post a Comment for "Javascript Anagram Comparison"