-2

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

  • 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 Answers2

0

Well,

  1. Learn JS.
  2. 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
-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.

  1. Only consider characters, no spaces or punctuation
  2. Consider capital letters to be the same as lowercase

Examples:

  1. anagrams(‘rail safety’, ‘fairy tales’) === true
  2. anagrams(‘RAIL! SAFETY!’, ‘fairy tales’) === true
  3. 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

https://medium.com/@hrusikesh251.nalanda/check-to-see-if-the-two-provided-strings-are-anagrams-of-each-other-9f9ddda89296

Hrusikesh
  • 185
  • 9