Hello everyone! I am new to this and would really appreciate some assistance. I am struggling with merging two arrays and removing duplicates. I know I might be over-complicating things, but I just can't figure it out.
// Merging two sorted arrays
// [1,3,5] + [3,4] ==> [1,3,4,5]
// [1, 2, 3, 5, 6, 7] + [3, 4] ==> [1, 2, 3, 4, 5, 6, 7]
function mergeArrays (array1, array2) {
var newArray = [];
var pointer1 = 0;
var pointer2 = 0;
// Both pointers are still within valid indexes
while (pointer1 < array1.length && pointer2 < array2.length) {
if (array1[pointer1] == array2[pointer2]) {
newArray.push(array1[pointer1]);
pointer1++;
pointer2++;
} else if (array1[pointer1] < array2[pointer2]) {
newArray.push(array1[pointer1]);
pointer1++;
} else if (array1[pointer1] > array2[pointer2]) {
newArray.push(array2[pointer2]);
pointer2++;
}
}
// Only one of the pointers is within a valid index
while (pointer1 < array1.length || pointer2 < array2.length) {
if (pointer1 >= array1.length && pointer2 < array2.length) {
newArray.push(array2[pointer2]);
pointer2++;
} else if (pointer2 >= array2.length && pointer1 < array1.length) {
newArray.push(array1[pointer1]);
pointer1++;
}
// Both pointers have reached the ends of the arrays
while (pointer1 == array1.length && pointer2 == array2.length) {
return newArray;
}
}
}