I need to create a javascript script that given two strings checks if one is the anagram of the other, I thought about using a check with support arrays but I don't know how to do it
Asked
Active
Viewed 138 times
-2
-
I think sorting both the arrays and compare them could be the easiest approach to quickly get there. Not the best algorithmically speaking.. but it could be made in one line – Diego D Dec 16 '22 at 13:39
-
i didn't try i have no idea how to make this script – Lorenzo Donadio Dec 16 '22 at 13:40
-
There are millions of examples in every existing language on the internet, have you tried googling before? – Konrad Dec 16 '22 at 13:45
-
Consider reading this [3 ways to solve the Anagram Algorithm Problem](https://medium.datadriveninvestor.com/3-ways-to-solve-the-anagram-algorithm-problem-61c2ba20b79e) – nima Dec 16 '22 at 13:46
-
Here you can find two approaches https://medium.com/@hrusikesh251.nalanda/check-to-see-if-the-two-provided-strings-are-anagrams-of-each-other-9f9ddda89296 – Hrusikesh Dec 16 '22 at 13:47
2 Answers
0
Well,
- Learn JS.
- Practice LeetCode DAILY.
For now, I hope this helps.
const checkForAnagram = (str1, str2) => {
// create, sort, then join an array for each string
const aStr1 = str1.toLowerCase().split('').sort().join('');
const aStr2 = str2.toLowerCase().split('').sort().join('');
return aStr1 === aStr2;
}
console.log(`The strings are anagrams: ${checkForAnagram('hello', 'ehlol')}`);
console.log(`The strings are anagrams: ${checkForAnagram('cat', 'rat')}`);

Dominic R.
- 53
- 6

Jason Francis
- 58
- 7
-1
Check to see if the two provided strings are anagrams of each other. One string is an anagram of another if it uses the same characters in the same quantity.
- Only consider characters, no spaces or punctuation
- Consider capital letters to be the same as lowercase
Examples:
- anagrams(‘rail safety’, ‘fairy tales’) === true
- anagrams(‘RAIL! SAFETY!’, ‘fairy tales’) === true
- anagrams(‘Hi there’, ‘Bye there’) === false
Let’s address this interview question using below two approaches
function testAnagrams(strA,strB){
//removing spaces and exclamation mark etc ... and converting into lowerCase
const cleanStrA = strA.replace(/[^\w]/g,"").toLowerCase();
const cleanStrB = strB.replace(/[^\w]/g,"").toLowerCase();
//creating array of characters form string
const firstArray = cleanStrA.split("");
const secondArray = cleanStrB.split("");
//sorting the array and again converting it into string with join method and checking if equal or not
if(firstArray.sort().join("") === secondArray.sort().join("")){
return true;
}else{
return false;
}
}
console.log(anagrams('rail safety', 'fairy tales'));
For more info visit

Hrusikesh
- 185
- 9