check if two strings are anagrams
character frequency map
[ Object.keys | length | regex | replace | for-of loop | for-in loop ]

Check if two strings are anagrams of each other

Write a function to check if two strings are anagrams of each other, returning true if they are anagrams, otherwise returns false.

Only alphanumeric characters will be considered and any whitespace or special characters or case will be ignored.


Anagrams

An anagram is a word or phrase formed by rearranging the letters of another word or phrase, typically using all the original letters exactly once. An anagram does not have to have the same meaning as the original word or phrase.


Example ...

Enter 2 strings ...

"Silent" string1

"listen" string2

The function will return true, both strings are anagrams of each other.

Both strings have the same length and the exact same letters appear exactly once; case is ignored.

The function will return false if both strings are not anagrams of each other.

Strings are a sequence of zero or more characters written inside quotes used to represent text.

Strings may consist of letters, numbers, symbols, words, or sentences.

Strings are immutable, they cannot be changed.

Each character in a string has an index.

The first character will be index 0 the second character will be index 1 and so on.

There are two ways to access an individual character in a string.

charAt() method

const str1 = "abc"; string

str1.charAt(0); character at index 0 → "a"

str1.charAt(1); character at index 1 → "b"

str1.charAt(2); character at index 2 → "c"

str1.charAt(3); character at index 3 → "" index not found

Alternatively use at() or slice() methods

bracket notation []

const str2 = "abc"; string

str2[0]; character at index 0 → "a"

str2[1]; character at index 1 → "b"

str2[2]; character at index 2 → "c"

str2[3]; character at index 3 → undefined index not found


Objects are a data structure used to store related data collections.

It stores data as key/value pairs, where each key is a unique identifier for the associated value.

Each key must be a string and must be unique, each value can be any data type.

If you define an object with duplicate keys, the last one will overwrite any preceding ones.

Find the value for any given key in the object.

const obj1 = {"A": 4, "B": 5, "C": 6 }; object

obj1["A"]; key "A"4

obj1["B"]; key "B"5

obj1["C"]; key "C"6

obj1["D"]; key "D"undefined key not found

Find the value for any given key in the object.

const obj2 = {"A": 4, "B": 5, "C": 6 }; object

const str = "ABC"; string

obj2[str[0]];4

obj2[str[1]];5

obj2[str[2]];6

obj2[str[3]];undefined key not found


Numbers are used to represent both integer and floating-point values.

Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴

let num1 = 5; → number

let num2 = 2.5; → number

let num3 = num1 + num2;

console.log(num3); returns ↴

7.5 → number


Check if two strings are anagrams using ↴

Object → data structure used to store related data collections as key/value pairs.

Object.keys() static method → returns an array of a given object's own enumerable string-keyed property names.

for...of loop → iterates through the values of an iterable object, such as an array, string, or map.

for...in loop → statement loops through the properties of an Object.

replace() method → returns a new string with the value(s) replaced.

Regular Expression → patterns used to match character combinations in strings.

toLowerCase() method → returns the value of the string converted to lower case.

length property → return the length of a string.


for...of loop iterates through the values of an iterable object, such as an Array, String, Set, Map, ...

syntax

for (variable of iterable) {}

variable holds the current value of the iteration.

of keyword indicates that the loop should iterate over the values of the iterable.

iterable object that is iterable, such as an Array, String, Set, Map, ...

Iterate over each character in the string.

const str3 = "ABC";

for (const char of str3) {

console.log(char);

} returns ↴

A

B

C → printed to console

The loop will run three times, once for each character in the string.

On each iteration, the value of the current element is stored in the variable char

For each iteration of the loop, the current value of char is printed to the console.


for...in loop iterates over the enumerable properties of an object. It allows access to each property key in the object one at a time.

Objects are collections of key/value pairs, where keys are strings (or Symbols) and values can be of any data type.

syntax

for (variable in object) {

// code block to be executed

}

variable holds the property name (key) of the current property on each iteration.

Variable can be declared with const, let, or var, depending on whether the key variable will be reassigned within the loop.

in keyword indicates that the loop should iterate over the enumerable properties of the specified object

object object whose enumerable properties are to be looped through.

Print each key/value pair from object.

const obj = { "A": 1, "B": 2, "C": 3 };

for (const key in obj) {

console.log(`${key}: ${obj[key]}`);

} returns ↴

A: 1

B: 2

C: 3 → printed to console

The variable key represents the current property name in the object obj

The loop will execute once for each property.

Use bracket notation obj[key] to access the value of the key from obj

console.log statement outputs the current key and its corresponding value


Count number of keys in an object.

const obj3 = { "A": 1, "B": 2, "C": 3 }; object

Object.keys(obj3).length; returns ↴

3 → there are 3 keys in the object → A B C


replace() method searches a string for a value or a regular expression and returns a new string with the value replaced.

If pattern is a string, only the first occurrence will be replaced. The original string is unchanged.

syntax

string.replace(pattern, replacement)

const str4 = "hello world";

str4.replace("hello", "HELLO"); replace "hello" with "HELLO"

returns ↴

"HELLO world"

const str5 = "ABCDEF";

str5.replace("B", ""); replace "B" with "" empty string

returns ↴

"ACDEF""B" removed from string


Regular expressions are patterns used to match character combinations in strings.

The Regular Expression /[^a-z0-9]/gi; matches the first letter of each word.

^ caret symbol beginning of a character class negates the set, meaning it matches any character not listed.

[^a-z0-9] character class matches any character that is not a lower case letter a to z or a digit 0 to 9

g flag indicates that the search should be global, meaning it will find all occurrences.

i flag makes the search case-insensitive, allowing it to match both upper case and lower case characters.


toLowerCase() method converts all letters to lower case. The original string is unchanged.

const str6 = "hELlo wORLd";

str6.toLowerCase(); returns ↴

"hello world" → lower case


length property returns the number of characters in a string.

const str7 = "Hello World";

str7.length; returns ↴

11 → there are 11 characters in the string


Initialize a variable to hold the first string.

const string1 = "silent"; → user input

Initialize a variable to hold the second string.

const string2 = "listen"; → user input


Define a function isAnagram() to check if two strings are anagrams.

function isAnagram(str1, str2) {}

The function takes two strings str1, str2 and checks if the two strings are anagrams.

If both strings are anagrams of each other, return true, otherwise return false. The original strings remains unchanged.

The code consists of a main function isAnagram that utilizes a helper function createCharMap

The helper function constructs a character frequency map for a given string.

The main function then compares these maps to determine if the two strings are anagrams.

Create a helper function to create a character frequency map.

function createCharMap(str) {} helper function

Initialize an empty object to hold character counts.

const charMap = {} charMap

Clean the string, remove non-alphanumeric characters and convert to lower case.

const newStr = str.replace(/[^a-z0-9]/gi, "").toLowerCase() newStr

Iterate over each character in the cleaned string.

for (const char of newStr) {}

char → current character

Increment the character count in the object.

charMap[char] = (charMap[char] || 0) + 1

If current character found in object.

charMap[char] = charMap[char] + 1 → increment the count by 1

If current character NOT found in object, add it to the object.

charMap[char] = 0 + 1 → initialize it to 0 and then add 1

Return the character frequency map.

return charMap charMap

Create character maps for both input strings.

const charMap1 = createCharMap(str1) charMap1

const charMap2 = createCharMap(str2) charMap2

Check if the number of unique characters is the same.

Object.keys returns a new array.

Object.keys(charMap1).length returns the number of keys held in the first array.

Object.keys(charMap2).length returns the number of keys held in the second array.

if (Object.keys(charMap1).length !== Object.keys(charMap2).length) {}

If lengths are different, they cannot be anagrams.

Return false and end execution of function.

return false

If lengths are the same,

compare the character counts in both maps.

for (const char in charMap1) {}

char → current character

If any character count differs, they are not anagrams.

if (charMap1[char] !== charMap2[char]) {}

If the character is not found or count is zero, strings are not anagrams of each other.

return false

If all checks pass, the strings are anagrams of each other.

return true

If the function returns true, strings are anagrams of each other

If the function returns false, strings are not anagrams of each other


Call the function with ↴

isAnagram(string1, string2);


Check if two strings are anagrams.

const string1 = "silent";

const string2 = "listen";

function isAnagram(str1, str2) {

helper function

function createCharMap(str) {

const charMap = {};

const newStr = str.replace(/[^a-z0-9]/gi, "").toLowerCase();

for (const char of newStr) {

charMap[char] = (charMap[char] || 0) + 1;

}

return charMap;

} end of helper function

const charMap1 = createCharMap(str1);

const charMap2 = createCharMap(str2);

if (Object.keys(charMap1).length !== Object.keys(charMap2).length) {

return false;

}

for (const char in charMap1) {

if (charMap1[char] !== charMap2[char]) {

return false;

}

}

return true;

}

call function

isAnagram(string1, string2); returns ↴

true


Anagram examples ↴

eleven plus two = twelve plus one

The Morse code = Here come dots

Vacation time = I am not active

Schoolmaster = The classroom

A gentleman = Elegant man

Astronomer = Moon starer

debit card = bad credit

iceman = cinema

silent = listen

Check if two strings are anagrams of each other