Skip to content

Instantly share code, notes, and snippets.

@avanishgiri
Last active December 30, 2015 02:39
Show Gist options
  • Save avanishgiri/7764020 to your computer and use it in GitHub Desktop.
Save avanishgiri/7764020 to your computer and use it in GitHub Desktop.
merge two sorted arrays, ignoring duplicates.
var merge_unique = function(array1, array2){
var len1 = array1.length;
var len2 = array2.length;
var buff = []
var i = 0, j = 0
while(i != len1 && j != len2){
if(array1[i] < array2[j])
buff.push(array1[i++]);
else
buff.push(array2[j++]);
while(array1[i] == buff[buff.length-1])
i++;
while(array2[j] == buff[buff.length-1])
j++;
}
for(i; i < len1; i++){
buff.push(array1[i]);
while(array1[i] == buff[buff.length-1])
i++;
}
for(j; j < len2; j++){
buff.push(array2[j]);
while(array2[j] == buff[buff.length-1])
j++;
}
return buff;
}
a1 = [1,2,3,4,5,6,7];
a2 = [3,4,5,6,7,8,9,10];
console.log(merge_unique(a1,a2));
console.log(merge_unique([],[]));
console.log(merge_unique([],[1]));
console.log(merge_unique([4],[1,1,1,1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment