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:
Javascript
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 outputconsole.log(checkAnagram('abc', 'cba')); |
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:
Javascript
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')); |
true
