View Full Version : Compare 2 Arrays

12-16-2011, 01:05 AM
I have 2 arrays and I would like to compare the 2 arrays.
If an element in array 1 is NOT in array 2 then I would like to display that element.

In this case, I should only display the letter "c" but it doesn't work and I don't know why??
Here's my code:

<script type="text/javascript">
function getValue(id){
var x=new Array("a","b","c","d","e");
var y=new Array("a","b","3","d","e");
var str="";

for (var i=0; i<x.length; i++){
for (var j=0; j<y.length; j++){
if (x[i] == y[j]){
//Check if reach the last element in the array 2
//If yes, then display that element in array 1 b/c not in array 2
if (y[j] == y.length-1){
str += x[i];
document.getElementById(id).innerHTML = str;


function init(){

<body onload="init()">
<h2 id="info"></h2>

12-16-2011, 05:12 AM
if (y[j] == y.length-1){

should be:

if (j == y.length-1){