How to Merge Two Sorted Lists in JavaScript

Merging two sorted lists in JavaScript can be achieved through a methodical approach, ensuring that the final list maintains the sorted order. This guide walks through the process of combining such lists.

Understanding the Merge Process

The essence of merging two sorted lists is to compare elements from both lists one by one and append the smaller element to the result list. We continue this process until all elements from both lists are included in the result list, ensuring it remains sorted.

Setting Up Your Lists

First, you need two pre-sorted arrays. For example:

let list1 = [1, 3, 5]; let list2 = [2, 4, 6];

Writing the Merge Function

Create a function that takes two sorted arrays as parameters:

function mergeSortedLists(arr1, arr2) { let merged = []; let i = 0, j = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { merged.push(arr1[i++]); } else { merged.push(arr2[j++]); } } // Append any remaining elements from arr1 or arr2 return [...merged, ...arr1.slice(i), ...arr2.slice(j)]; }

Executing the Merge

To merge the lists, call the mergeSortedLists function with your sorted lists:

let sortedList = mergeSortedLists(list1, list2);

Tips for Optimizing the Merge

  • Keep track of the current index in both arrays to avoid unnecessary iterations.
  • Use a while loop to ensure that elements are compared as long as both arrays have unmerged items.
  • After one list is exhausted, concatenate the remaining elements of the other list, as they are already sorted.

Handling Edge Cases

Consider the possibility of different length arrays or empty arrays. The function above accounts for these scenarios by using the spread operator to concatenate any remaining elements after the main while loop.

Testing Your Function

Always test the merge function with various list combinations to ensure its reliability:

console.log(mergeSortedLists([1, 2, 3], [4, 5, 6])); // [1, 2, 3, 4, 5, 6] console.log(mergeSortedLists([1, 3, 5], [2])); // [1, 2, 3, 5] console.log(mergeSortedLists([], [2, 4, 6])); // [2, 4, 6]

Following this guide, JavaScript engineers can merge sorted lists with confidence, enhancing their data manipulation capabilities within any application.

Invite only

We're building the next generation of data visualization.