Search code examples
javascriptiterationanagram

Why is this anagram function not correct?


Just got back my test for my Javascript class and I missed a question that I felt quite certain about.

We were supposed to make a function that returned true if two strings were anagrams, and false otherwise. I cant find an instance where this wouldn't work. I would appreciate any help!

This is what I had:

function isAnagram(str1, str2){
    if(str1.length !== str2.length){
        return false;
    }
    else{
        for(var i = 0; i < str1.length; i++){
            if(!str2.includes(str1[i])){
                return false;
            }
         }
         return true;
     }
}

Solution

  • It only checks that each letter of str1 is present in str2, regardless of how many times they appear.

    EDIT: It also doesn't check if str2 has letters that don't appear in str1.

    function isAnagram(str1, str2) {
      if (str1.length !== str2.length) {
        return false;
      } else {
        for (var i = 0; i < str1.length; i++) {
          if (!str2.includes(str1[i])) {
            return false;
          }
        }
        return true;
      }
    }
    
    console.log(isAnagram('hello', 'hlleo'), ', should be true'); // true: correct
    console.log(isAnagram('bye', 'byee'), ', should be false'); // false: correct
    console.log(isAnagram('byeb', 'byee'), ', should be false'); // true: incorrect
    console.log(isAnagram('byeb', 'byte'), ', should be false'); // true: incorrect