JavaScript Snippet

Merge and Sort Two Arrays

Difficulty: Medium

Merging two arrays of numbers is the kind of task whose right answer depends entirely on whether the inputs are already sorted. This snippet shows three patterns: a simple concat-then-sort for small or unsorted inputs, the classic two-pointer linear merge for already-sorted inputs, and an in-place variant that fills a preallocated buffer for hot paths. Pick by input shape and size, not by habit.

Code Snippets
/

Merge and Sort Two Arrays

Merge and Sort Two Arrays

Merging two arrays of numbers is the kind of task whose right answer depends entirely on whether the inputs are already sorted. This snippet shows three patterns: a simple concat-then-sort for small or unsorted inputs, the classic two-pointer linear merge for already-sorted inputs, and an in-place variant that fills a preallocated buffer for hot paths. Pick by input shape and size, not by habit.

JavaScript
Medium
3 snippets
arrays
sorting
array-manipulation-patterns

1,107 views

15

This is the right default when the inputs are not already sorted, when the combined size is small (under a few thousand items), or when readability matters more than micro-optimization. Time complexity is O((n + m) log(n + m)) because the engine sorts the concatenated result. The mandatory comparator ((x, y) => x - y) is the single biggest gotcha: omit it and Array.prototype.sort coerces values to strings and sorts lexicographically, which produces wrong order for any number with two or more digits.