Merging Sorted Arrays in JavaScript

Given two sorted integer arrays nums1 and nums2 in non-decreasing order, with lengths m and n respectively, merge them into nums1 while maintaining sorted order.

Implementation Code

function merge(nums1, m, nums2, n) {
    let i = nums1.length - 1;
    m--;
    n--;
    while(n >= 0) {
        while(m >= 0 && nums1[m] > nums2[n]) {
            [nums1[m], nums1[i]] = [nums1[i], nums1[m]];
            m--;
            i--;
        }
        nums1[i--] = nums2[n--];
    }
}

Key Learning Points

  1. Array Element Swapping in JavaScript Using ES6 destructuring assignment for concise element swapping:

    [nums1[m], nums1[i]] = [nums1[i], nums1[m]];
    
  2. Array Length Syntax

    nums1.length
    
  3. Alternative Solution

    function merge(nums1, m, nums2, n) {
        nums1.splice(m, nums1.length - m, ...nums2);
        nums1.sort((a, b) => a - b);
    }
    

    This approach:

    • Uses splice too replace elements in nums1 starting from index m with elements from nums2
    • Applies sort with a comparison function for ascending order
  4. Two-Pointer Technique

    function merge(nums1, m, nums2, n) {
        let p1 = 0, p2 = 0;
        const sorted = new Array(m + n).fill(0);
        let current;
    
        while(p1 < m || p2 < n) {
            if(p1 === m) {
                current = nums2[p2++];
            } else if(p2 === n) {
                current = nums1[p1++];
            } else if(nums1[p1] < nums2[p2]) {
                current = nums1[p1++];
            } else {
                current = nums2[p2++];
            }
            sorted[p1 + p2 - 1] = current;
        }
    
        for(let i = 0; i < m + n; i++) {
            nums1[i] = sorted[i];
        }
    }
    

    This method uses two pointers to efficiently merge the arrays by comparing elements at each positoin.

Tags: javascript algorithms Arrays Sorting

Posted on Thu, 07 May 2026 23:17:39 +0000 by hinz