Alex Rivera | Logout

Simplest code for array intersection in javascript

Asked 2009-12-11T03:04:04.823
1089

What's the simplest, library-free code for implementing array intersections in javascript? I want to write

intersection([1,2,3], [2,3,4,5])

and get

[2, 3]
Edit
Report

1 Answer

-5

"filter" and "indexOf" aren't supported on Array in IE. How about this:

var array1 = [1, 2, 3];
var array2 = [2, 3, 4, 5];

var intersection = [];
for (i in array1) {
    for (j in array2) {
        if (array1[i] == array2[j]) intersection.push(array1[i]);
    }
}
answered 2009-12-11T05:42:33.890

Your Answer