- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checking for string anagrams JavaScript
Anagrams
Anagrams are those string pair, one of which when reordered in a certain pattern yields the other one.
For example −
'hello' and 'lolhe' are anagrams because we can reorder 'lolhe' to form the string 'hello' or vice-versa.
We are required to write a JavaScript function that takes in two strings, say str1 and str2. The function should return true if the strings are anagrams of each other, false otherwise.
We can create a map that tallies the number of characters for each input string. Then, we can compare the maps to see if they are identical.
Example
const str1 = 'hello'; const str2 = 'lolhe'; const charCount = string => { const table = {}; for (let char of string.replace(/\W/g, "").toLowerCase()) table[char] = table[char] + 1 || 1; return table; }; const anagrams = (stringA, stringB) => { const charCountA = charCount(stringA); const charCountB = charCount(stringB); if (Object.keys(charCountA).length !== Object.keys(charCountB).length) return false; for (let char in charCountA) if (charCountA[char] !== charCountB[char]) return false; return true; }; console.log(anagrams(str1, str2));
Output
And the output in the console will be −
true
- Related Articles
- Checking for uniqueness of a string in JavaScript
- JavaScript - Checking for pandigital numbers
- Checking for overlapping times JavaScript
- Checking for co-prime numbers - JavaScript
- Checking for convex polygon in JavaScript
- Checking for increasing triplet in JavaScript
- Checking an array for palindromes - JavaScript
- Checking for Fibonacci numbers in JavaScript
- Checking for straight lines in JavaScript
- JavaScript Array: Checking for multiple values
- Checking for coprime numbers in JavaScript
- Checking for ascending arrays in JavaScript
- Checking for special numbers in JavaScript
- Checking for the Gapful numbers in JavaScript
- Checking for centrally peaked arrays in JavaScript

Advertisements