Skip to content
the poor coder

check for string anagram javascript

Poor Man
Published
Reading time
1 min read
On this page

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.

JavaScript

      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.

JavaScript

      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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC