I have a working array comparison (tested with different kind of code), which looks like this:
var a = [0,1,2] var b = [1,2] var match = [] var miss = [] func(a,b, match, miss); function func(a, b, matches, misses) { for (var i=0; i<b.length; i++) { for (var j=0; j<a.length; j++) { if (b[i] == a[j]) { console.log("Found"); matches.push(b[i]) } } } console.log("Matches: " + matches); console.log("Misses: " + misses); }
It works usually fine. However this time it doesn't. I have two arrays which have a different size (a is bigger than b) and can have different content like "100.AB 12345".
I can't explain why my function doesn't work in that case. Can someone help me out? It doesn't find any matches, everything is a miss, even though they are matches.
I think it's this line:
if (b[j] == a[j])
Should the b[j]
be b[i]
? As a
is bigger than b
, using the j
indexer would be attempting to reference after the end of b
.
Hello check the below code it will work fine even a is bigger than b or b is bigger than a
var a = ['a','ab','c','d','e']; var b = ['ef','f','ab','a']; var a1,b1; var match = []; var miss = []; var temp_a=a.length; var temp_b=b.length; if( temp_a > temp_b){ a1=b; b1=a; }else{ a1=a; b1=b; } func(a1,b1, match, miss); function func(a, b, matches, misses) { for (var i=0; i<b.length; i++) { for (var j=0; j<a.length; j++) { if (b[i] == a[j]) { console.log("Found"); matches.push(b[i]) } } } console.log("Matches: " + matches); console.log("Misses: " + misses); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.