JavaScript anagram comparison

前端 未结 16 2107
走了就别回头了
走了就别回头了 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 02:44

    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."
        );
    }
    

提交回复
热议问题