Anagram Check in JavaScript

Sort both strings. If they match, anagram. Listen and silent.

IntermediateString ProgramsExample 4 of 5
anagram-check.js
1// Anagram: Same characters, different order
2// Examples: "listen" and "silent", "evil" and "vile"
3
4// Method 1: Sort and compare
5function isAnagram1(str1, str2) {
6 // Normalize: lowercase, remove spaces
7 str1 = str1.toLowerCase().replace(/\s/g, '');
8 str2 = str2.toLowerCase().replace(/\s/g, '');
9
10 // Sort and compare
11 return str1.split('').sort().join('') ===
12 str2.split('').sort().join('');
13}
14
15console.log("listen & silent:", isAnagram1("listen", "silent"));
16console.log("hello & world:", isAnagram1("hello", "world"));
17console.log("The Morse Code & Here come dots:",
18 isAnagram1("The Morse Code", "Here come dots"));
19
20// Method 2: Character frequency count
21function isAnagram2(str1, str2) {
22 str1 = str1.toLowerCase().replace(/\s/g, '');
23 str2 = str2.toLowerCase().replace(/\s/g, '');
24
25 if (str1.length !== str2.length) return false;
26
27 let count1 = {};
28 let count2 = {};
29
30 // Count characters in str1
31 for (let char of str1) {
32 count1[char] = (count1[char] || 0) + 1;
33 }
34
35 // Count characters in str2
36 for (let char of str2) {
37 count2[char] = (count2[char] || 0) + 1;
38 }
39
40 // Compare counts
41 for (let char in count1) {
42 if (count1[char] !== count2[char]) {
43 return false;
44 }
45 }
46
47 return true;
48}
49
50console.log("\nUsing frequency:");
51console.log("listen & silent:", isAnagram2("listen", "silent"));
52console.log("aabb & abab:", isAnagram2("aabb", "abab"));
53
54// Method 3: Single object count
55function isAnagram3(str1, str2) {
56 str1 = str1.toLowerCase().replace(/\s/g, '');
57 str2 = str2.toLowerCase().replace(/\s/g, '');
58
59 if (str1.length !== str2.length) return false;
60
61 let count = {};
62
63 // Increment for str1
64 for (let char of str1) {
65 count[char] = (count[char] || 0) + 1;
66 }
67
68 // Decrement for str2
69 for (let char of str2) {
70 if (!count[char]) return false;
71 count[char]--;
72 }
73
74 return true;
75}
76
77console.log("\nSingle object:");
78console.log("evil & vile:", isAnagram3("evil", "vile"));

Output

listen & silent: true
hello & world: false
The Morse Code & Here come dots: true

Using frequency:
listen & silent: true
aabb & abab: true

Single object:
evil & vile: true

What's going on

split('').sort().join('') on both. Skip lowercasing and Listen vs silent fails.

Spaces: decide whether they count. This page usually strips them.