PDA

View Full Version : Comparing Two Arrays, printing matches



thesprucegoose
04-01-2009, 02:06 PM
Greetings,

I'm attempting to compare two arrays and print all of the results into a <div>.

In this case, I'd like to compare numArray with stringSplit and have the resulting matches (which in the case I'm printing is numArray[0], numArray[1], and numArray[3]) and have those matches print from nameArray. So in the case I'm printing, I want the <div id=captainContent> to print nameArray[0], nameArray[1], and nameArray[3].

Code is not working. Anyone see any issues?

Thanks,

--thesprucegoose




var testString = "10-20-40";
var element = document.getElementById("captainContent");
var numArray = new Array();
numArray[0] = "10";
numArray[1] = "20";
numArray[2] = "30";
numArray[3] = "40";
numArray[4] = "50";

var nameArray = new Array();
nameArray[0] = "Ten";
nameArray[1] = "Twenty";
nameArray[2] = "Thirty";
nameArray[3] = "Forty";
nameArray[4] = "Fifty";



var stringSplit = testString.split("-");

for (i = 0; i < stringSplit.length; i++) {
for (j = 0; j < numArray.length; i++) {
if (stringSplit[i] == numArray[j]) {
element.innerHTML += nameArray[j] + '<br />';
}
}


}

jscheuer1
04-01-2009, 02:26 PM
The code has some other basic issues, but if that's the general approach you want to take, here:


for (i = 0; i < stringSplit.length; i++) {
for (j = 0; j < numArray.length; i++) {
if (stringSplit[i] == numArray[j]) {
element.innerHTML += nameArray[j] + '<br />';
}
}


}

That i should be j.

thesprucegoose
04-01-2009, 02:32 PM
Oh no! :eek:

Now I feel silly. Thank you so much!