0

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:

<html><head>
<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]){
       	    break;
	 }else{
            //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(){
   getValue("info");
}
</script>
</head>

<body onload="init()">
<h2 id="info"></h2>
</body>
</html>
2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by Airshow
0

Hiyatran,

It's easier with a found variable inside the outer loop to track of whether the inner loop has found the current x.

function getValue(id){
	var x = ["a","b","c","d","e"];
	var y = ["a","b","3","d","e"];
	var i, j, found, notFound = [];
	for(i=0; i<x.length; i++){
		found = false;
		for(j=0; j<y.length; j++){
			if(x[i] == y[j]){
				found = true;
				break;
			}
		}
		if(!found){
			notFound.push(x[i]);
		}
	}
	document.getElementById(id).innerHTML = notFound.join(', ');
}

(untested)

Using exactly the same logic, it's slightly more concise with the jQuery lib:

function getValue2(id){
	var x = ["a","b","c","d","e"];
	var y = ["a","b","3","d","e"];
	var notFound = [];
	$(x).each(function(){
		if($.inarray(this,y)==-1){
			notFound.push(this);
		}
	});
	$('#'+id).html(notFound.join(', '));
}

(untested)

Airshow

Edited by Airshow: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.