Intersection of Two Arrays

The introduction of new Array and Object methods back in 2009 greatly simplified the task of comparing two arrays to see if there are any elements that appear in both. Instead of having nested for loops we can use the new methods instead.

If all we need is to determine whether there is any overlap between the content of the two arrays then the Array.some() method is ideal for the purpose since it simply needs to have a condition specified that will return true or false and will automatically stop as soon as it finds a true condition. The comparison we need here is only slightly more complicated in that we need to nest a second Array.some() inside the first so that we can compare against all the elements in the second array and not just the first one

var compare = function(a,b) {
return a.some(function(i) {return b.some(function(j) {return i===j;});});

Suppose though that instead of just checking if the two arrays have any common values we instead want to extract those common values into a new array. We can't use some() for this as it will stop once the first match is found. Instead we use the more generic forEach() instead. With this method we no longer want to return whether a match was found but if one was then we want to add it to the results. Now if we add the matched value as a property to an object instead of as a value in an array, we can automatically drop any duplicates as they will simply update the same property. We can then use Object.keys() to convert those properties to an array once we are finished and know that we have an array that contains all of the elements that appear at least once in both of the original arrays but with no duplications in the intersection array.

var compare2= function(a,b) {
var c = {};
a.forEach(function(i) {b.forEach(function(j) {if(i===j) c[i] = '';});});

Either of these functions uses only a small fraction of the code that a solution using nested for loops would use. In addition both of these unlike the for loops will ignore any missing entries in either array where the for loops would create those missing entries and give them a value of undefined - which would result in an extra entry being added to the results if there were gaps in both of the original arrays. In addition the second version removes the duplicates simply by using slightly different commands from the ones you would use to simply add the results to an array and so completely avoids the need for any extra code to remove the duplicates after the result array has been built.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow