Merging two sorted arrays into one sorted array using JavaScript

We are required to write a JavaScript function that takes in two sorted arrays of numbers. Our function should merge all the elements of both arrays into a new array and return that new array sorted in the same order.

Two-Pointer Approach

The most efficient approach uses two pointers to traverse both arrays simultaneously, comparing elements and adding the smaller one to the result array.

const arr1 = [1, 3, 4, 5, 6, 8];
const arr2 = [4, 6, 8, 9, 11];

const mergeSortedArrays = (arr1 = [], arr2 = []) => {
    const res = [];
    let i = 0;
    let j = 0;
    
    // Compare elements and add smaller one
    while(i < arr1.length && j < arr2.length){
        if(arr1[i] < arr2[j]){
            res.push(arr1[i]);
            i++;
        }else{
            res.push(arr2[j]);
            j++;
        }
    }
    
    // Add remaining elements from arr1
    while(i < arr1.length){
        res.push(arr1[i]);
        i++;
    }
    
    // Add remaining elements from arr2
    while(j < arr2.length){
        res.push(arr2[j]);
        j++;
    }
    
    return res;
};

console.log(mergeSortedArrays(arr1, arr2));
[ 1, 3, 4, 4, 5, 6, 6, 8, 8, 9, 11 ]

How It Works

The algorithm maintains two pointers i and j for arrays arr1 and arr2 respectively. It compares elements at current positions and adds the smaller element to the result, then advances the corresponding pointer. After one array is exhausted, remaining elements from the other array are added.

Alternative: Using Spread and Sort

A simpler but less efficient approach combines both arrays and sorts the result:

const arr1 = [1, 3, 4, 5, 6, 8];
const arr2 = [4, 6, 8, 9, 11];

const mergeAndSort = (arr1, arr2) => {
    return [...arr1, ...arr2].sort((a, b) => a - b);
};

console.log(mergeAndSort(arr1, arr2));
[ 1, 3, 4, 4, 5, 6, 6, 8, 8, 9, 11 ]

Comparison

Method Time Complexity Space Complexity Efficiency
Two-Pointer O(m + n) O(m + n) Optimal for sorted arrays
Spread + Sort O((m + n) log(m + n)) O(m + n) Simpler but slower

Conclusion

The two-pointer approach is the most efficient method for merging sorted arrays with O(m + n) time complexity. Use the spread and sort method only for simplicity with small datasets.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements