I have two integer arrays which contain numeric values. I want to look through both lists and check for commonality (or lack of) between the lists. I.e. I want to iterate th
Sort both arrays, than loop just once and compare:
function diff(arrayToCompareTo, comparedArray)
{
Sort(arrayToCompareTo);
Sort(comparedArray);
var difference = [], same = [];
for(var i = 0; i < arrayToCompareTo.length; ++i)
{
if (arrayToCompareTo[i] != comparedArray[i])
difference.push(comparedArray[i]);
else
same.push(comparedArray[i]);
}
if (comparedArray.length > arrayToCompareTo.length)
for(var i = arrayToCompareTo.length; i < comparedArray.length; ++i)
difference.push(comparedArray[i]);
}
This is not tested so if something is wrong please let me know.
Anyway this should set you to the right direction since it's O(N) at best and O(M) at worst if comparedArray.length > arrayToCompareTo.length, it's much more efficient than O(N^2). Note that the sorting takes O(N log N).