Ad

You are given two arrays of integers, sorted in ascending order. Your task is to write a function that merges the two arrays, and output a merged array that is also sorted. But there's the catch! The Array.prototype.sort() function is not available!

For example, given the following two arrays:

[0, 3, 6, 13, 45]
[-1, 45, 330, 553]

Your function should return:

[-1, 0, 3, 6, 13, 45, 45, 330, 553]

Note that there may be duplicates. It's fine to leave them in there.

function mergeArrays(arrA, arrB) {
  const output = [];
  const arrAClone = [...arrA];
  const arrBClone = [...arrB];
  let nextSmallestA = arrAClone.shift();
  let nextSmallestB = arrBClone.shift();
  while (nextSmallestA !== undefined || nextSmallestB !== undefined) {
      if (nextSmallestA === undefined || nextSmallestB < nextSmallestA) {
        output.push(nextSmallestB);
        nextSmallestB = arrBClone.shift();
      } else {
        output.push(nextSmallestA);
        nextSmallestA = arrAClone.shift();
      }
  }
  return output;
}