My current code:
function intersect(first, second) {
var temp = [];
for(var i = 0; i < first.length; i++){
for(var k = 0; k < second.length; k++){
if(first[i] == second[k]){
temp.push( first[i]);
break;
}
}
}
return temp;
}
How can I change this so it returns ALL the intersections indices?
asked Mar 10, 2015 at 17:41
Y. Zhang
1931 gold badge5 silver badges18 bronze badges
2 Answers 2
You need to add the indices to your result;
function intersect(first, second) {
var temp = [];
for(var i = 0; i < first.length; i++){
for(var k = 0; k < second.length; k++){
if(first[i] == second[k]){
temp.push([i, k]); // push i and k as an array
}
}
}
return temp;
}
Also remove the break; if you want recurring exact intersections to be selected also.
Find a running example here: http://jsfiddle.net/0tL9sk5w/1
Sign up to request clarification or add additional context in comments.
3 Comments
Oceanity
Correct me if I'm wrong, but won't that break statement cause it to only return the first match in the second array?
Rias
Indeed, if in the second array a second exact same intersection occurs it is filtered by the break, so it has to be removed. I will edit it accordingly, thanks.
Y. Zhang
thank you... can't believe i didn't catch this part in all my attemtps temp.push([i, k])
All you need to do is to push the two indexes as an array
instead of :
temp.push( first[i]);
you need to do this :
temp.push([i,k]);
answered Mar 10, 2015 at 17:49
Khalid
4,8285 gold badges29 silver badges50 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js