How to check a given string is an anagram of another string in JavaScript ?
In this article, we will learn how to check a given string is an anagram of another string in JavaScript. Before that, we should learn what is an anagram.
An anagram is a word or sentence, which usually contains all the original letters exactly once, in order to arrange the letters of a different term or phrase. Some of the examples are given below:
- evil = vile
- a gentleman = elegant man
- eleven plus two = twelve plus one
There are many approaches through which we can compare a string as an anagram of another string:
Approach 1: Using split(), sort(), and join() Methods
In this article, we will use in-built functions such as split(), sort(), and join() to check if a given string is an anagram of another string in JavaScript.
Example:
function checkAnagram(a, b) {
// Not of same length, can't be Anagram
if (a.length !== b.length) {
return false;
}
// Inbuilt functions to rearrange the string
let str1 = a.split('').sort().join('');
let str2 = b.split('').sort().join('');
let result = (str1 === str2);
return result;
}
// Checking the output
console.log(checkAnagram('abc', 'cba'));
Output
true
Approach 2: Using for loop
In this article, we will the javascript for loop to check if a given string is an anagram of another string in JavaScript.
Example:
function checkAnagram(a, b) {
let array = {};
if (a === b) {
return true;
}
if (a.length !== b.length) {
return false;
}
let minCharCode = Math.min(getMinCharCode(a),
getMinCharCode(b));
for (let i = 0; i < a.length; i++) {
let res = a.charCodeAt(i) - minCharCode;
array[res] = (array[res] || 0) + 1;
}
for (let j = 0; j < b.length; j++) {
let res = b.charCodeAt(j) - minCharCode;
if (!array[res]) {
return false;
}
array[res]--;
}
return true;
}
function getMinCharCode(str) {
let minCharCode = Infinity;
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
if (charCode < minCharCode) {
minCharCode = charCode;
}
}
return minCharCode;
}
console.log(checkAnagram('abc', 'cba'));
Output
true
Approach 3: Using a Frequency Map
Using a frequency map to check anagrams involves creating maps for both strings, where each character's count is recorded. By comparing these maps, if all character counts match, the strings are anagrams.
Example :
const areAnagrams = (str1, str2) => {
if (str1.length !== str2.length) return false;
const frequencyMap = (str) => {
const map = {};
for (let char of str) {
map[char] = (map[char] || 0) + 1;
}
return map;
};
const map1 = frequencyMap(str1);
const map2 = frequencyMap(str2);
for (let char in map1) {
if (map1[char] !== map2[char]) return false;
}
return true;
};
console.log(areAnagrams("listen", "silent")); // true
console.log(areAnagrams("hello", "world")); // false
Output
true false