Concatenate sorted arrays and remove duplicate javascript
I came up with this to combine two sorted arrays and remove duplicates. I want to know if I can do better.
Any ideas?
var mergeArrays = function(arr1 , arr2){
var mergedArray = new Array();
var i = 0, j=0,k=0;
var prev = -1;
while(arr1.length > i || arr2.length > j){
if(arr1[i] == arr2[j]){
mergedArray[k] = arr1[i];
i++;
j++;
}else if(arr1[i] < arr2[j] || arr2[j] == undefined){
mergedArray[k] = arr1[i];
i++;
}else{
if(arr2[j]>prev) {
mergedArray[k] = arr2[j];
}
j++;
}
prev = mergedArray[k];
k++;
}
return mergedArray;
}
+3
source to share
3 answers
I would do it this way
function unique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
var array1 = ["...",",,,"];
var array2 = ["///", "..."];
var array3 = unique(array1.concat(array2));
0
source to share