Axel
Axel

Reputation: 83

Anagram with JavaScript

const myAnagram = (arr1, arr2) => {
  let str1 = arr1;
  let str2 = arr2;
  let temp1 = [];
  let temp2 = [];
  let flag = 0;

  if (str1.length !== str2.length) return "Not Anagram statement A";

  for (var i = 0; i < str1.length - 1; i++) {
    temp1[i] = str1[i];
  }

  for (var j = 0; j < str2.length - 1; j++) {
    temp2[i] = str2[i];
  }

  temp1.sort();
  temp2.sort();

  for (var k = 0; k < str1.length - 1; k++) {
    if (temp1[j] !== temp2[j]) return "Not Anagram statement C";
    return "Anagram! statement D";
  }
}

Upvotes: 0

Views: 2262

Answers (3)

Ananthaprakash
Ananthaprakash

Reputation: 131

find two strings are equal size compare the characters and the count of characters matches

const isAnagram = (str1, str2) => {
   const compare = (first, next) => {
    return first.split('').sort().join('') === next.split('').sort().join('');
   }
   return str1.length !== str2.length ? false : compare(str1, str2);
 }

Upvotes: 1

mmende
mmende

Reputation: 301

Your loops always skip the last elements since you use < together with str1.length - 1. You should either use
for (var i = 0; i < str1.length; ++i) {...} or
for (var i = 0; i <= str.length-1; ++i) {...}

Furthermore in your comparison loop you already return when the first characters match (or when they don't). Therefore the loop will never compare the second (or nth) characters. The loop should further compare the characters until you are sure the arrays differ at some point.

You can shrink the function like

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

    var arr1 = arr2 = []
    for (var i = 0; i < str1.length; ++i) {
        arr1[i] = str1[i]
        arr2[i] = str2[i]
    }

    arr1.sort()
    arr2.sort()

    for (var i = 0; i < arr1.length; ++i)
        if (arr1[i] !== arr2[i]) return false
    return true
}

And then

if (isAnagram("frog","rg0f")) {
    console.log("Anagram!")
} else {
    console.log("Not Anagram.")
}

Upvotes: 0

Abhijit Misra
Abhijit Misra

Reputation: 156

The problem you have is with the identifiers you have used in loops. Have a look at the corrected code.

function myAnagram(arr1, arr2) {

    var str1 = arr1;
    var str2 = arr2;
    var temp1 = [];
    var temp2 = [];
    var flag = 0;
    if (str1.length !== str2.length) {
        return "Not Anagram statement A";
    } else {
        for (var i = 0; i < str1.length; i++) {
            temp1[i] = str1[i];
        }

        for (var j = 0; j < str2.length; j++) {
            temp2[j] = str2[j];
        }
        temp1.sort();
        temp2.sort();
        for (var k = 0; k < str1.length; k++) {
            if (temp1[k] !== temp2[k]) {
                return "Not Anagram statement C";
            } else {
                return "Anagram! statement D";
            }
        }
    }
}

Hope it helps !! PS: You can optimize this code to a great extend.

Upvotes: 1

Related Questions