Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to check a given string is an anagram of another string in JavaScript ?
Next article icon

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

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using split(), sort(), and join() Methods
  • Using for loop
  • Using a Frequency Map

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 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:

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'));  

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 :

JavaScript
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 

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

P

priyavermaa1198
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JavaScript-Properties
  • JavaScript-DSA
  • JavaScript-Methods
  • JavaScript-Questions

Similar Reads

    Javascript Program To Check If A String Is Substring Of Another
    Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :  Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
    2 min read
    JavaScript - How to Check if a String "StartsWith" Another String in JavaScript?
    Here are the various methods to check if a string starts with another string in JavaScript1. Using String.startsWith() MethodThe most widely used method is the startsWith() method, built into JavaScript. This method is simple to use, highly readable, and performs the task efficiently.JavaScriptlet s
    3 min read
    Check two given strings are isomorphic in JavaScript
    Two strings are said to be isomorphic if it is possible to map every character of the first string to every character of the second string. Basically, in isomorphic strings, there is a one-to-one mapping between every character of the first string to every character of the second string. We can also
    5 min read
    How to check a string is entirely made up of the same substring in JavaScript ?
    We are given a string and the task is to determine whether the string is made up of the same substrings or not. 1. Using Regular Expression with test() method Initialize a string to the variable.Use the test() method to test a pattern in a string.The test() method returns true if the match is found,
    3 min read
    Check if two strings are permutation of each other in JavaScript
    In this approach, we are going to discuss how we can check if two strings are permutations of each other or not using JavaScript language. If two strings have the same number of characters rather than having the same position or not it will be a permutation. Example: Input: "pqrs" , "rpqs"Output: Tr
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences