I have trouble dealing with my for loops now, I’m trying to compare two datum, basically it will compare 2 items, then it will write the matches and the mismatches on the webpage.
I managed to write the matches on the webpage, it was working good. But there’s a bug in my mismatch compare.
It wrote all the data on the webpage X times, here’s my JS code:
function testItems(i1, i2) { var newArray = []; var newArray2 = []; var count = 0; var count2 = 0; for(var i = 0; i < i1.length; i++) { for(var j = 0; j < i2.length; j++) { if(i1[i] == i2[j]) { newArray.push(i1[i]); count++; } if (i1[i] !== i2[j]) { newArray2.push(i1[i]); count2++; } } } count-=2; count2-=2 writeHTML(count,count2, newArray, newArray2); }
The result was horrible for the mismatches:
alt text http://www.picamatic.com/show/2009/03/01/07/44/2523028_672x48.jpg
I was expecting it to show the mistakes, not all the strings.
The issue you’re seeing is because of the nested for loop. You are essentially doing a cross-compare: for every item in i1, you are comparing it to every item in i2 (remember that j starts again at 0 every time i advances… the two loops don’t run in parallel).
Since I understand from the comments below that you want to be able to compare one array to the other, even if the items in each are in a different order, I’ve edited my original suggestion. Note that the snippet below does not normalize differences in case between the two arrays… don’t know if that’s a concern. Also note that it only compares i1 against i2… not both i1 to i2 and i2 to i1, which would make the task a little more challenging.
As an alternative, you could consider using a hash table to index i1/i2, but since the example of strings in your comment include spaces and I don’t know if you’re using any javascript helper libraries, it’s probably best to stick with the nested for loops. The snippet also makes no attempt to weed out duplicates.
Another optimization you might consider is that your newArray and newArray2 arrays contain their own length property, so you don’t need to pass the count to your HTML writer. When the writer receives the arrays, it can ask each one for the .length property to know how large each one is.