©2018  LUVCODING                             

HUDDERSFIELD

UK

luvcoding
  • Grey Facebook Icon
  • Grey Twitter Icon
  • Grey Google+ Icon
  • Grey YouTube Icon
  • Grey Pinterest Icon
luvcodings.com

Luvcodings  JAVASCRIPT

Anagrams

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word anagram can be rearranged into nag a ram, or the word binary into brainy.

The original word or phrase is known as the subject of the anagram. Any word or phrase that exactly reproduces the letters in another order is an anagram.

Simple example of anagram

<!DOCTYPE html>
<Html>
    <head>
        <Title>"JAVASCRPTS LESSONS "</Title>
    </head>
    
    <Body>
        <h2>******JavaScript Solutions**********</h2>           
        <p>Question: Take two strings, return yes if they are anagram:</p>
        <p>String1: pan:</p>
        <p>String2: nap:</p>

        <script>
            //Declare string 1
            var str1= "pan";
            var str2= "nap";
            var str11= str1.split('')// converts the string to a list;
            var str22= str2.split('').reverse()//converts the string to a list, the reverse
                            
            // Now lets iterate over the strings to see if they anagram
            
            //using filter function
            function Anagrams(a, b) {
                if (a.length==b.length){
                    var same = (function(){
                    return a.filter(function(i) {return b.indexOf(i)>= 0;});
                        })();
                    console.log(same);
                    console.log(same.length, a.length)
                    if (same.length===a.length){
                        
document.getElementById("demo").innerHTML="Yes they are anagram"
                    }else  { document.getElementById("demo1").innerHTML="Yes they are anagram"}
                    
                }else {alert("arrays are not equal");}
            }

            
            function Get_the_Result(){
                Anagrams(str11, str22);
            }
        </script>
     
        <input type='button' id='button' value="Result" onclick="Get_the_Result()" />
         <p id="demo"></p>
         <p id="demo1"></p>
    </Body>
</Html>

Sample Output