How to Combine Two Sorted Arrays in JavaScript for Beginners

When working with arrays in JavaScript, a common task is merging two sorted arrays into a single sorted array. This blog post will walk you through a simple yet effective way to accomplish this using a while loop and conditional checks. If you are looking for a beginner-friendly approach to solving this problem, you’re in the right place! Let’s break down the code step by step.

Understanding the Code

The goal of this JavaScript code is to merge two sorted arrays (firstArray and secondArray) into a single sorted array called combinedArray.

// Define two sorted arrays
const firstArray = [1, 3, 5, 7, 9, 11];
const secondArray = [2, 4, 6, 8];

// Initialize an empty array that will hold the merged result
const combinedArray = [];

// Initialize three pointers
// i for firstArray, j for secondArray, and k for combinedArray
let i = 0, j = 0, k = 0;

// Merge both arrays while there are elements in both
while (i < firstArray.length && j < secondArray.length) {
    // Compare the elements of both arrays at their respective pointers
    if (firstArray[i] < secondArray[j]) {
        // If element from firstArray is smaller, add it to combinedArray
        combinedArray[k] = firstArray[i];
        // Move to the next element in firstArray
        i++;
    } else {
        // Otherwise, add the element from secondArray to combinedArray
        combinedArray[k] = secondArray[j];
        // Move to the next element in secondArray
        j++;
    }
    // Move to the next position in combinedArray
    k++;
}

// After one of the arrays is fully traversed, append the remaining elements from firstArray (if any)
while (i < firstArray.length) {
    combinedArray[k] = firstArray[i];
    i++;
    k++;
}

// After one of the arrays is fully traversed, append the remaining elements from secondArray (if any)
while (j < secondArray.length) {
    combinedArray[k] = secondArray[j];
    j++;
    k++;
}

// Output the merged array
console.log(combinedArray);

Why This Approach Works

The reason why this approach works so well is because both arrays are already sorted. By comparing the elements at the current pointers (i and j), we can directly place the smallest element in the correct position in combinedArray without needing to re-sort it later.

This is the core idea behind many sorting and merging algorithms, like Merge Sort, which is an efficient, divide-and-conquer sorting algorithm.

If you want to find an element from an array without using the array method, read it here.

Conclusion

Merging two sorted arrays is a common task, and the code above provides a straightforward method to achieve this in JavaScript. By understanding this logic, you can tackle more complex array manipulation tasks in the future. Whether you’re preparing for coding interviews or improving your JavaScript skills, this pattern is fundamental and worth mastering.

Happy coding!

You May Also Like

More From Author