Returning the non-intersection of two arrays

They have: 3 posts

Joined: May 2009

Ive got 2 arrays, array1 and array2, that store integer values. Id like a function that takes the two arrays and returns an array with every value that is in array1 and not array2 and array2 but not array1, so:

array1(1,2,3,4,5,6)
array2(3,4,5,6,7,8 )

nonIntersect(array1, array2) = array(1,2,7,8 )

The order of elements is not important.

Javascripts inbuilt array functions dont seem to helpful for this. The only way i can think to perform this would be to iterate over every value in array1 against everything from array2. There has to be a better way!

Cheers for any feedback

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Does this have to be JS and not server side?

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

You're trying to calculate the difference between the two arrays, in PHP, that's easy using the array_diff() function.

There is also a Javascript function here.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.