Dev Helpers
← Back

Merge sorted arrays

Merge sorted arrays. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const merge = (a, b) => {
  const out = [];
  let i = 0,
    j = 0;
  while (i < a.length && j < b.length)
    out.push(a[i] <= b[j] ? a[i++] : b[j++]);
  return out.concat(a.slice(i), b.slice(j));
};
console.log(merge([1, 4, 7], [2, 3, 8]));

Sample output

[ 1, 2, 3, 4, 7, 8 ]