Skip to content
Related Articles

Related Articles

Improve Article

How to check a given string is an anagram of another string in JavaScript ?

  • Difficulty Level : Expert
  • Last Updated : 06 Apr, 2021

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:

1. evil = vile

2. a gentleman = elegant man

3. eleven plus two = twelve plus one

Example 1: Using in-built functions.



HTML




<script>
    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
        var str1 = a.split('').sort().join(''); 
        var str2 = b.split('').sort().join('');
  
        var result = (str1 === str2);
        return result;
    }
  
    // Checking the output
    document.write(checkAnagram('abc', 'cba'));
</script>

Output:

true

Example 2: Without using inbuilt functions.

HTML




<script>
    function checkAnagram(a, b) {
        var array = {};
        if (a === b) {
            return true;
        }
        if (a.length !== b.length) {
            return false;
        }
        for (let i = 0; i < a.length; i++) {
            let res = a.charCodeAt(i) - 97;
            array[res] = (array[res] || 0) + 1;
        }
  
        for (let j = 0; j < b.length; j++) {
            let res = b.charCodeAt(j) - 97;
            if (!array[res]) {
                return false;
            }
            array[res]--;
        }
        return true;
    }
    document.write(checkAnagram('abc', 'cba'));
</script>

Output:

true



My Personal Notes arrow_drop_up
Recommended Articles
Page :