Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Compare 2 arrays

Status
Not open for further replies.

hiyatran

Technical User
Aug 7, 2010
21
CA
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 == 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;
}
}
}
}
document.getElementById(id).innerHTML = str;

}


function init(){
getValue("info");
}
</script>
</head>

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

 
Hi

You compared the array length against the array element instead of the array index :
Code:
[b]if[/b] [teal]([/teal][highlight]j[/highlight] [teal]==[/teal] y[teal].[/teal]length[teal]-[/teal][purple]1[/purple][teal])[/teal][teal]{[/teal]


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top