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?

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

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]);

Comments

Your Answer

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.