check for string anagram javascript
Checking for String Anagram in Javascript
String anagram refers to a situation where two strings have the same characters but in a different order. For instance, "listen" and "silent" are anagrams. We can use Javascript to check whether two strings are anagrams or not.
Method 1: Sort and Compare
One way to solve this problem is to sort both strings and compare them. If both strings are anagrams, sorting them will result in the same string.
function isAnagram(str1, str2) {
let sortedStr1 = str1.split('').sort().join('');
let sortedStr2 = str2.split('').sort().join('');
return sortedStr1 === sortedStr2;
}
console.log(isAnagram('listen', 'silent')); // true
Method 2: Using Frequency Counters
Another way of solving this problem is by using frequency counters. In this approach, we create an object that will hold the frequency of each character in both strings. We then compare the frequency of each character in both objects. If the frequencies are the same, then the strings are anagrams.
function isAnagram(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
let frequencyCount1 = {};
let frequencyCount2 = {};
for (let char of str1) {
frequencyCount1[char] = (frequencyCount1[char] || 0) + 1;
}
for (let char of str2) {
frequencyCount2[char] = (frequencyCount2[char] || 0) + 1;
}
for (let key in frequencyCount1) {
if (!(key in frequencyCount2)) {
return false;
}
if (frequencyCount1[key] !== frequencyCount2[key]) {
return false;
}
}
return true;
}
console.log(isAnagram('listen', 'silent')); // true
These are two of the most efficient ways of checking for string anagram in Javascript. Choose the one that best suits your needs.