JOIN DEVPPL

It looks like you are new here. If you want to get involved, click on Join below!



Compare 2 Arrays


H

keyboard_arrow_up
1
keyboard_arrow_down


First Post Mark as Spam hiyatran
Posts: 18 - Registered: 2010-06-20 20:53:36

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>




M

keyboard_arrow_up
0
keyboard_arrow_down


Reply #1 Mark as Spam mohamedzarmeda
Posts: 3 - Registered: 2013-09-29 19:18:00

my too
The same problem I suffer from it




J

keyboard_arrow_up
0
keyboard_arrow_down


Reply #2 Mark as Spam joesimmons
Posts: 5 - Registered: 2013-09-06 14:02:57

If you have Array.prototype.forEach and Array.prototype.indexOf in your browser, you could do this:

function getValue(id) {
var x = ["a", "b", "c", "d", "e"];
var y = ["a", "b", "3", "d", "e"];
var str = "";

y.forEach(function (currentItem, currentIndex) {
if ( x.indexOf(currentItem) === -1 ) {
str += x[currentIndex];
}
});

document.getElementById(id).innerHTML = str;
}






JOIN DEVPPL

It looks like you are new here. If you want to get involved, click on Join below!




MENU
Advertising