Created
May 8, 2020 20:55
-
-
Save danilodorgam/ced819e3f03343c945fb5f67ac76d3f9 to your computer and use it in GitHub Desktop.
getCommonElements https://codereview.stackexchange.com/questions/96096/find-common-elements-in-a-list-of-arrays
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 arrays = [ | |
[1, 4, 6, 78, 8, 9, 124, 44], | |
[44, 6, 9], | |
[124, 44, 16, 9] | |
]; | |
function getCommonElements(arrays){//Assumes that we are dealing with an array of arrays of integers | |
var currentValues = {}; | |
var commonValues = {}; | |
for (var i = arrays[0].length-1; i >=0; i--){//Iterating backwards for efficiency | |
currentValues[arrays[0][i]] = 1; //Doesn't really matter what we set it to | |
} | |
for (var i = arrays.length-1; i>0; i--){ | |
var currentArray = arrays[i]; | |
for (var j = currentArray.length-1; j >=0; j--){ | |
if (currentArray[j] in currentValues){ | |
commonValues[currentArray[j]] = 1; //Once again, the `1` doesn't matter | |
} | |
} | |
currentValues = commonValues; | |
commonValues = {}; | |
} | |
return Object.keys(currentValues).map(function(value){ | |
return parseInt(value); | |
}); | |
} | |
console.log(getCommonElements(arrays)); //Prints [9,44] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment