Emmanuel Akinfulubi

JavaScriptArray

Merge two sorted arrays in JavaScript

Advanced · 4 min read

You have two lists that are already sorted, say two pages of search results or two sorted files, and you need one sorted list. The quick answer is to join them and sort again. That works, but it throws away the order you already had. Merging walks both lists once, side by side, and builds the result in a single pass.

In this tutorial you will write merge, make it work on objects as well as numbers, and then use it to build merge sort, one of the classic sorting algorithms. You should know arrays, while loops, slice and the spread syntax .... Stability and recursion are explained below.

Merging by hand

Picture two sorted piles of cards, face up. Look at the top card of each pile, take the smaller one, and put it on your output pile. Repeat. When one pile runs out, the other pile is already in order, so you put it on top as it is.

Output

left: 1 4 7   right: 2 3 9
take 1 (1 < 2)   take 2 (4 > 2)   take 3 (4 > 3)
take 4 (4 < 9)   take 7 (7 < 9)   left is empty, add 9
result: 1 2 3 4 7 9

Each card is looked at once, so merging two lists of n items takes about 2n steps.

Stable merging

Sometimes two items compare as equal, like two orders that cost the same. A merge is stable if equal items keep their original order: on a tie, it takes from the left list first. That matters when you sort records by one field and want an earlier sort, say by date, to survive among the ties. JavaScript's own sort is stable, and our merge will be too.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

52 Merge two sorted lists

hard

Merge two already-sorted lists into one sorted list in a single pass, without concatenating and re-sorting. Then build merge sort out of it.

Stuck? Three hints, smallest first
  1. 1. Two indexes, one per list. Take the smaller head, advance that index.
  2. 2. When one list runs out, everything left in the other is already sorted — append it.
  3. 3. <= rather than < on the comparison is what makes the merge stable.

Step 1: two indexes

Keep one index for each list. i points at the next unused item of a, and j at the next unused item of b. While both lists still have items, take the smaller head:

Step 1

const a = [1, 4, 7];
const b = [2, 3, 9];
const out = [];
let i = 0;
let j = 0;

while (i < a.length && j < b.length) {
  out.push(a[i] <= b[j] ? a[i++] : b[j++]);
}

console.log(out, i, j); // [ 1, 2, 3, 4, 7 ] 3 2

a[i++] reads a[i] first, then adds one to i. So one expression takes the item and moves past it. The loop stops when a runs out: i is 3, while b still has one item left, the 9.

Step 2: add what's left

Whatever remains in either list is already sorted, and every item in it is at least as big as everything in out. So it goes on the end as it is:

Step 2

function merge(a, b) {
  const out = [];
  let i = 0;
  let j = 0;
  while (i < a.length && j < b.length) {
    out.push(a[i] <= b[j] ? a[i++] : b[j++]);
  }
  return [...out, ...a.slice(i), ...b.slice(j)];
}

console.log(merge([1, 4, 7], [2, 3, 9])); // [ 1, 2, 3, 4, 7, 9 ]
console.log(merge([], [1, 2]));           // [ 1, 2 ]
console.log(merge([], []));               // []
console.log(merge([1, 1], [1]));          // [ 1, 1, 1 ]

At most one of the two slices has anything in it. The other is empty, and spreading an empty array adds nothing. That also handles an empty input on either side without any special case.

A common wrong turn is to stop after the loop and return out. That loses the 9, and in general everything left in the longer list.

Step 3: ties and the key function

To merge records, the function needs to know which field to compare. A key parameter does that. It defaults to (x) => x, which returns the value unchanged, so numbers still work with no extra argument.

Step 3

function merge(a, b, key = (x) => x) {
  const out = [];
  let i = 0;
  let j = 0;
  while (i < a.length && j < b.length) {
    out.push(key(a[i]) <= key(b[j]) ? a[i++] : b[j++]);
  }
  return [...out, ...a.slice(i), ...b.slice(j)];
}

const left = [{ v: 1, side: 'L' }];
const right = [{ v: 1, side: 'R' }];
console.log(merge(left, right, (x) => x.v).map((x) => x.side)); // [ 'L', 'R' ]

Both records have v equal to 1. Because the test is <=, a tie takes from the left list, so 'L' comes out first. With < instead, the right record would win ties and the merge would no longer be stable.

Step 4: merge sort

Merge sort turns the merge into a full sorting algorithm with recursion, a function calling itself on a smaller piece. A list of zero or one items is already sorted. Any longer list is split in half, each half is sorted by the same function, and the two sorted halves are merged:

Step 4

function merge(a, b, key = (x) => x) {
  const out = [];
  let i = 0;
  let j = 0;
  while (i < a.length && j < b.length) {
    out.push(key(a[i]) <= key(b[j]) ? a[i++] : b[j++]);
  }
  return [...out, ...a.slice(i), ...b.slice(j)];
}

function mergeSort(xs) {
  if (xs.length <= 1) return xs.slice();
  const mid = Math.floor(xs.length / 2);
  return merge(mergeSort(xs.slice(0, mid)), mergeSort(xs.slice(mid)));
}

const data = [5, 3, 8, 1, 9, 2];
console.log(mergeSort(data)); // [ 1, 2, 3, 5, 8, 9 ]
console.log(data);            // [ 5, 3, 8, 1, 9, 2 ]

[5, 3, 8, 1, 9, 2] splits into [5, 3, 8] and [1, 9, 2], those split again, and so on down to single items. Then the merges build sorted lists back up. The input is never changed, because every step works on slices, which are copies.

Step 5: check against sort

A simple way to trust the merge is to compare it with the slow way:

Step 5

function merge(a, b) {
  const out = [];
  let i = 0;
  let j = 0;
  while (i < a.length && j < b.length) {
    out.push(a[i] <= b[j] ? a[i++] : b[j++]);
  }
  return [...out, ...a.slice(i), ...b.slice(j)];
}

const left = [1, 4, 7];
const right = [2, 3, 9];
const viaSort = [...left, ...right].sort((x, y) => x - y);

console.log(JSON.stringify(merge(left, right)) === JSON.stringify(viaSort)); // true
console.log(left, right); // [ 1, 4, 7 ] [ 2, 3, 9 ]

Same answer, and both inputs are unchanged. The difference is the work: the merge reads each item once, while sorting the joined list starts over as if the order were unknown.

The full solution

The panel has merge with its key parameter and mergeSort built on it. It merges two lists, checks the tie order with two records, and sorts six numbers. Press Run.

The answer

function merge(a, b, key = (x) => x) {
  const out = [];
  let i = 0;
  let j = 0;
  while (i < a.length && j < b.length) {
    out.push(key(a[i]) <= key(b[j]) ? a[i++] : b[j++]);      // <= : ties take from a
  }
  return [...out, ...a.slice(i), ...b.slice(j)];             // whatever is left is sorted
}

function mergeSort(xs) {
  if (xs.length <= 1) return xs.slice();
  const mid = Math.floor(xs.length / 2);
  return merge(mergeSort(xs.slice(0, mid)), mergeSort(xs.slice(mid)));
}

const left = [1, 4, 7];
const right = [2, 3, 9];

const tiedLeft = [{ v: 1, side: 'L' }];
const tiedRight = [{ v: 1, side: 'R' }];
const tied = merge(tiedLeft, tiedRight, (x) => x.v).map((x) => x.side);

const merged = merge(left, right);

console.log('left    :', left);
console.log('right   :', right);
console.log('merged  :', merged);
console.log('sorted? :', merged.every((v, i) => i === 0 || merged[i - 1] <= v));
console.log('ties    :', tied, '<- the left-hand element first');
console.log('one empty:', merge([], [1, 2]));
console.log('mergeSort:', mergeSort([5, 3, 8, 1, 9, 2]));
console.log('inputs afterwards:', left, right);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('two sorted lists become one', merged, [1, 2, 3, 4, 7, 9]);
test('the result is in order', merged.every((v, i) => i === 0 || merged[i - 1] <= v), true);
test('it agrees with concatenating and re-sorting', merged, [...left, ...right].sort((x, y) => x - y));
test('an empty list on either side returns the other', [merge([], [1, 2]), merge([1, 2], [])], [[1, 2], [1, 2]]);
test('two empty lists give an empty list', merge([], []), []);
test('duplicates are all kept', merge([1, 1], [1]), [1, 1, 1]);
test('a tie takes from the left list first, which makes it stable', tied, ['L', 'R']);
test('the inputs are not modified', [left, right], [[1, 4, 7], [2, 3, 9]]);
test('merge sort is this function plus recursion', mergeSort([5, 3, 8, 1, 9, 2]), [1, 2, 3, 5, 8, 9]);

Merging is linear: each element is looked at once, so two lists of n cost 2n. [...a, ...b].sort() throws that away and pays n log n to rediscover an ordering you already had. On two sorted pages of results, or two sorted files too big to hold at once, the difference is the whole point.

<= versus < looks like a detail and is the definition of stability. With <=, equal elements come out of a before b, so a merge sort built on it preserves the original relative order of ties — which is exactly the guarantee Array.prototype.sort makes, and exercise 27 relied on.

The key parameter is what makes it usable on records rather than numbers. It defaults to the identity function, so the simple case stays simple.

Common mistakes

  • Returning out straight after the loop. The leftover items of the longer list are lost. Append both slices.
  • Comparing with < instead of <=. Ties then come from the right list, and the merge is no longer stable.
  • Merging lists that aren't sorted. The result isn't sorted either. Merging relies on both inputs being in order.

Try it yourself

  1. Merge two lists of people by age using the key parameter.
  2. Write mergeMany(lists) that merges any number of sorted lists. (Hint: reduce with merge.)
  3. Change merge to drop duplicates, so merge([1, 2], [2, 3]) gives [1, 2, 3].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.