Created
September 16, 2017 16:24
-
-
Save kuzmicheff/c02953aea46e8b0cd57bb037d460bebf to your computer and use it in GitHub Desktop.
Array intersection in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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