Marco Santos
Marco Santos

Reputation: 1005

Check for Anagram in 2 strings

I've created a function that checks if 2 words are anagrams, but I want to make it better. I feel the declaration of the counter after in the if statement is not quite well, if anybody have a better solution would be great.

function checkAnagram(string1, string2){

        if(string1.length !== string2.length){
            return false;
        }

        for(var i = 0; i < string1.length; i++){

            if(count <= 0){

                return false;
            }
            var count = 0;

            for(var t = 0; t < string2.length; t++){

                //counter = 0

                if(string2[t].toLowerCase() == string1[i].toLowerCase()){
                    //counter++;
                    count++;
                    break;
                }


            }

        }

        return true;
    }

Upvotes: 4

Views: 8434

Answers (6)

K Shaikh
K Shaikh

Reputation: 401

Here is a bit different approach:

function isAnagram(one, two) {
  const copyOne = one.split('');
  const copyTwo = two.split('');
  if (copyOne.length === copyTwo.length) {
    for (let i=0; i<=copyOne.length; i++) {
      const letterAt = copyTwo.indexOf(copyOne[i]);
      if (letterAt > -1) copyTwo.splice(letterAt, 1);
    }
    if (copyTwo.length === 0) return true;
    else return false;
  }
  return false;
}

console.log(isAnagram((one = "anagram"), (two = "nagaram")));

Upvotes: 0

Aakash Rathore
Aakash Rathore

Reputation: 1

function isAnagram(str1, str2){
    if(str1.length !== str2.length){
        return false
    }

    let string1 = str1.toLowerCase().split('').sort().join('');
    let string2 = str2.toLowerCase().split('').sort().join('');
    return string1 === string2
}
isAnagram('abcdef', 'AbcFed')

Upvotes: 0

4nkitpatel
4nkitpatel

Reputation: 178

If you don't want to use prebuild methods like .split() .sort() .join() then

function isAnagrams(stringA, stringB) {
      // just to remove special char and convert it to lowercase
      stringA = stringA.replace(/[^\w]/g, "").toLowerCase();
      stringB = stringB.replace(/[^\w]/g, "").toLowerCase();
      if (stringA.length !== stringB.length) return false;
      let aCharMap = {};
      let bCharMap = {};
      /* 
        making of mapObject of both string, containing character as property and 
        count of that character as value 
      */
      for (let i = 0; i < stringA.length; i++) {
        bCharMap[stringB[i]] = bCharMap[stringB[i]] + 1 || 1;
        aCharMap[stringA[i]] = aCharMap[stringA[i]] + 1 || 1;
      }
      //  checking both CharMap value
      for (let q of stringB) {
        if (bCharMap[q] !== aCharMap[q]) {
          return false;
        }
      }
      return true;
}  

console.log(`isAnagram : ${isAnagrams('rail safety', 'fairy tales')}`)

so if you pass isAnagrams('rail safety','fairy tales'); then character map will look like this

aCharMap = { r: 1, a: 2, i: 1, l: 1, s: 1, f: 1, e: 1, t: 1, y: 1 }
bCharMap = { f: 1, a: 2, i: 1, r: 1, y: 1, t: 1, l: 1, e: 1, s: 1 }

then we will compare if they have same value or not based on that result will be decided

Upvotes: 1

sai krishna
sai krishna

Reputation: 51

function checkAnagram(string1, string2) {
   return string1.replace(/[^\w]/g,'').toLowerCase().split('').sort().join('') === 
        string2.toLowerCase().replace(/[^\w]/g,'').split('').sort().join('')
}

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115488

Here is a much easier way of doing it:

var s1 = "test"
var s2 = "tset"

function testAnagram (s1, s2){

 if(!s1 || !s2 || s1.length !== s2.length){return false;}

 var lS1 = s1.toLowerCase();
 var lS2 = s2.toLowerCase();

 if(lS1 === lS2) {return false;}

 var rS1 = lS1.split('').sort().join('');
 var rS2 = lS2.split('').sort().join('');

 return rS1 === rS2;
}



var result = testAnagram(s1, s2);

alert(result);

Upvotes: 15

jbargu
jbargu

Reputation: 96

Your code returns true for strings 'aabb' and 'abcc', which are not anagrams. You can just sort the strings and check if they're equal:

function checkAnagram(string1, string2) {
   return string1.toLowerCase().split("").sort().join("") === string2.toLowerCase().split("").sort().join("")
}

Upvotes: 8

Related Questions