JavaScript anagram comparison

前端 未结 16 2113
走了就别回头了
走了就别回头了 2020-12-17 02:30

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 \"

16条回答
  •  情歌与酒
    2020-12-17 03:06

    Here's my contribution, I had to do this exercise for a class! I'm finally understanding how JS works, and as I was able to came up with a solution (it's not - by far - the best one, but it's ok!) I'm very happy I can share this one here, too! (although there are plenty solutions here already, but whatever :P )

    function isAnagram(string1, string2) {
        // first check: if the lenghts are different, not an anagram 
        if (string1.length != string2.length)
            return false
        else {
        // it doesn't matter if the letters are capitalized, 
        // so the toLowerCase method ensures that...
            string1 = string1.toLowerCase()
            string2 = string2.toLowerCase()
            
        // for each letter in the string (I could've used for each :P)
            for (let i = 0; i < string1.length; i++) {
                // check, for each char in string2, if they are NOT somewhere at string1
                if (!string1.includes(string2.charAt(i))) {
                    return false
                }
                else {
                    // if all the chars are covered 
                    // and the condition is the opposite of the previous if
                    if (i == (string1.length - 1))
                        return true
                }
            }
        }
    }
    

提交回复
热议问题