Last active
August 29, 2015 14:20
-
-
Save unkleara/8d6d2ec76420166d354b to your computer and use it in GitHub Desktop.
Had issue's properly solving this so I spent some time going over it.
This file contains hidden or 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
//two seperate arrays with some duplicate numbers | |
//use object to hold values from larger array as keys | |
//compare second/smaller array against object.keys from first/larger array | |
//add duplicates to new array and return new array | |
var ArrayDuplicateFinder = (function() { | |
//Private variable | |
var arrayHash = {}; | |
var module = { | |
run : run, | |
found : { data: null }, | |
clear : clearData | |
}; | |
return module; | |
function run(first, second) { | |
if (!Array.isArray(first) || !Array.isArray(second)) { | |
return console.log('Not valid Array or Arrays'); | |
} | |
//empty if array has existing elements | |
if(module.found.data) clearData(); | |
checkArraySize(first, second, function(largeArray, smallArray) { | |
mapObjectTo(largeArray, function() { | |
compareWith(smallArray, function(dups) { | |
module.found.data = dups; | |
}); | |
}); | |
}); | |
} | |
function clearData() { | |
module.found.data.length = 0; | |
arrayHash = {}; | |
} | |
function checkArraySize(first, second, callback) { | |
//Note: Equal length arrays will work the same when mapped to object since same elements will be | |
// checked against object key | |
if (first.length == second.length) return callback(first, second); | |
//We want larger array for mapping keys to avoid missing elements from smaller array | |
var larger = first.length > second.length ? first : second; | |
var smaller = first.length < second.length ? first : second; | |
callback(larger, smaller); | |
} | |
function mapObjectTo(largerArray, done) { | |
for (var i=0; i < largerArray.length; i++) { | |
arrayHash[largerArray[i]] = largerArray[i]; | |
} | |
return done(); | |
} | |
function compareWith(small, callback) { | |
var dups = []; | |
small.forEach(function(el) { | |
if (arrayHash.hasOwnProperty(el)) { | |
dups.push(el); | |
} | |
}); | |
callback(dups); | |
} | |
}()); | |
var arrayA = [2, 5, 4, 6, 7, 10, 1], | |
arrayB = [4, 8, 1, 11, 15, 9, 22]; | |
var ADF = ArrayDuplicateFinder; | |
ADF.run(arrayA, arrayB); | |
//ADF.run(arrayB, arrayA); | |
var results = ADF.found.data; | |
console.log(results); | |
//alert(results); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment