Javascript Data Type How to - Compare two arrays and output matched values








Question

We would like to know how to compare two arrays and output matched values.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--   w w  w .j  a va 2  s  .  c o m-->
var a = [1,2,3,5,7];
var b = [4,7,5,5];
for(i=0;i<a.length;i++)
{
    var bl = false;
    for(j=0;j<b.length;j++)
    {
        if(a[i] == b[j])
        {
            bl = true;
        }
    }
    if(bl)
        document.writeln("find match for : " + a[i]);
}

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

The code above is rendered as follows: