JSFiddle - React, Tailwind, and code Playground

by prozoroff

JavaScript

const arr1 = [1, 2, 3];
const arr2 = [2, 6, 9];

const merge = (a, b) => {
	const result = [];
	const resultLength = a.length + b.length;

	let indA = 0;
	let indB = 0;
	let maxA = a[indA];
	let maxB = b[indB];

	while (result.length < resultLength) {
		while (indA < a.length && (a[indA] <= maxB || indB >= b.length)) {
			result.push(a[indA]);
			indA += 1;
		}
		maxA = a[indA];

		while (indB < b.length && (b[indB] <= maxA || indA >= a.length)) {
			result.push(b[indB]);
			indB += 1;
		}
		maxB = b[indB];
	}

	return result;
};

const mergeShift = (a, b) => {
	const result = [];

	while (a.length || b.length) {
		while (a.length && (!b.length || a[0] <= b[0])) {
			result.push(a.shift());
		}
		while (b.length && (!a.length || b[0] < a[0])) {
			result.push(b.shift());
		}
	}

	return result;
};

console.log(mergeShift(arr1, arr2));