0

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

2 Answers 2

3

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

answered Mar 10, 2015 at 17:47
Sign up to request clarification or add additional context in comments.

3 Comments

Correct me if I'm wrong, but won't that break statement cause it to only return the first match in the second array?
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.
thank you... can't believe i didn't catch this part in all my attemtps temp.push([i, k])
2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.