check if two strings are anagrams
Object
[ for-loop | for...in loop | regEx | replace | length | toLowerCase ]

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


Check if two strings are anagrams using ↴

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

for loop → executes a block of code a number of times.

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 loop repeatedly executes a block of code until a specified condition evaluates to false.

The loop runs a block of code a set number of times, defined by an initialization, a condition, and an increment.

for (let x = 0; x < 4; x++) {

console.log(x);

}

Loop variable x is initialized to 0

Condition x < 4 is checked before each iteration.

The loop will continue to run as long as x is less than 4

The loop repeatedly executes a block of code 4 times, from 0 to 3

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

After each iteration, x is incremented by 1 x++

When x reaches 4 the condition evaluates to false, terminating the loop.

0

1

2

3 → printed to 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


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 str3 = "hello world";

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

returns ↴

"HELLO world"

const str4 = "ABCDEF";

str4.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 str5 = "hELlo wORLd";

str5.toLowerCase(); returns ↴

"hello world" lower case


length property returns the number of characters in a string.

const str6 = "Hello World";

str6.length; returns ↴

11 There are 11 characters in the string


Initialize a variable to hold the first string to compare.

const string1 = "silent"; → user input

Initialize a variable to hold the second string to compare.

const string2 = "listen"; → user input


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

function isAnagram(str1, str2) {}

The function removes all non-alphanumeric characters and converts all characters to lower case.

If the length of each string is the same, the occurrences of each character found in each string is counted.

The character counts for each string are compared to determine if the strings are anagrams.

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.

Remove non-alphanumeric characters and convert all characters to lower case.

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

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

Check if the lengths of the cleaned strings are equal.

if (str1.length !== str2.length) {}

If length of each string is different they cannot be anagrams.

Return false and end execution of function.

return false

If both strings have the same length.

Initialize objects to hold character counts for both string.

let count1 = {} count1

let count2 = {} count2

Count frequency of each character in str1

for (let x = 0; x < str1.length; x++) {}

Get the character at index x

let char = str1[x] char

Increment the count if current character found.

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

If current character found in object.

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

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

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

Count frequency of each character in str2

for (let x = 0; x < str2.length; x++) {}

Get the character at index x

let char = str2[x] char

Increment the count if current character found.

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

If current character found in object.

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

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

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

Compare character counts from both strings.

for (let char in count1) {}

If counts do not match, they are not anagrams.

if (count1[char] !== count2[char]) {}

Return false if counts differ.

return false

Return true if all counts match.

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) {

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

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

if (str1.length !== str2.length) {

return false;

}

let count1 = {};

let count2 = {};

for (let x = 0; x < str1.length; x++) {

let char = str1[x];

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

}

for (let x = 0; x < str2.length; x++) {

let char = str2[x];

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

}

for (let char in count1) {

if (count1[char] !== count2[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