I want to combine two arrays in JavaScript. Unfortunately, comparing the specific data that I use is expensive. What is the best algorithm for combining my lists with the least number of comparisons?
EDIT: I have to note that the two arrays are sorted, and I would like the merged content to be sorted and only have unique values.
EDIT: upon request I will give you my current code, but that really doesn't help.
merge = function(arr1,arr2) {
if(!arr1.length) {
Array.prototype.push.apply(arr1,arr2);
return;
}
var j, lj;
for(var s, i=0, j=0, li=arr1.length, lj=arr2.length; i<li && j<lj;) {
s = compare(arr1[i], arr2[j]);
if(s<0) ++i;
else if(s==0) ++i, ++j;
else arr1.splice(i,0, arr2[j++]);
}
if(j<lj) Array.prototype.push.apply(arr1, arr2.slice(j));
};
source
share