Skip to content

Instantly share code, notes, and snippets.

@danilodorgam
Created May 8, 2020 20:55
Show Gist options
  • Save danilodorgam/ced819e3f03343c945fb5f67ac76d3f9 to your computer and use it in GitHub Desktop.
Save danilodorgam/ced819e3f03343c945fb5f67ac76d3f9 to your computer and use it in GitHub Desktop.
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