shake demo

Click to shake the box.

Wednesday, 20 November 2013

JavaScript Array - Check if array has Duplicate/Repeated Values/Repeated Numbers/Characters

<html>
<head>
<script language="javascript">

var X = new Array( 
        "Aniruddha",
        "Deepak",
        "Pooja",
        "Ryo",
        "Kaori",
        "Maya",
        "Aniruddha"               
    );
// we can also put numbers in " " instead of characters or string

function arrHasDupes( A ) {                          // finds any duplicate array elements using  possible comparison
    var i, j, n;
    n=A.length;
                                                     // to ensure possible comparisons
    for (i=0; i<n; i++) {                        // outer loop uses each item i at 0 through n
        for (j=i+1; j<n; j++) {              // inner loop only compares items j at i+1 to n
            if (A[i]==A[j]) return true;
    }    }
    return false;
}

if ( arrHasDupes( X ) )                            
    document.write("There is repeated Value in array:  ", X);
else
    document.write("There is no repeated Value in array:  ", X);

</script>
</head>
<body>
</body>
</html>

No comments:

Post a Comment