Skip to content

Instantly share code, notes, and snippets.

@kuzmicheff
Created September 16, 2017 16:24
Show Gist options
  • Save kuzmicheff/c02953aea46e8b0cd57bb037d460bebf to your computer and use it in GitHub Desktop.
Save kuzmicheff/c02953aea46e8b0cd57bb037d460bebf to your computer and use it in GitHub Desktop.
Array intersection in JavaScript
var arrayIntersection = function(firstArray, secondArray) {
var outputArray = [];
firstArray.forEach(function(firstArrayItem) {
secondArray.forEach(function(secondArrayItem) {
if (secondArrayItem === firstArrayItem) {
if (outputArray.length !== 0) {
if (outputArray.indexOf(secondArrayItem) === -1) {
outputArray.push(secondArrayItem);
}
}
else {
outputArray.push(secondArrayItem);
}
}
});
});
return outputArray;
};
var array1 = [ 7, 2, 7, 4, 1 ];
var array2 = [ 7, 3, 2, 5 ];
console.log(arrayIntersection(array1, array2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment