VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-merge-two-sorted-arrays/

⇱ JavaScript- Merge two Sorted Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript- Merge two Sorted Arrays

Last Updated : 23 Jul, 2025

These are the following ways to merge two sorted arrays:

1. Using Two Pointers (Efficient For Large Arrays)

This approach involves using two pointers, one for each array, and comparing their elements as you iterate through them. This method works efficiently in O(n + m) time, where n and m are the lengths of the two arrays.


Output
[
 1, 2, 3, 4,
 5, 6, 7, 8
]

2. Using concat() and sort() (Less Efficient)

You can merge both arrays using concat() and then use sort() to sort the merged array. However, this method has a time complexity of O((n + m) * log(n + m)), where n and m are the lengths of the arrays, due to the sorting step.


Output
[
 1, 2, 3, 4,
 5, 6, 7, 8
]

3. Using push() in a Loop (Manual Merge and Less Efficient)

This approach manually merges the arrays using push() without explicitly using two pointers or the sort() function. It iterates through both arrays and adds the elements in sorted order.


Output
[
 1, 2, 3, 4,
 5, 6, 7, 8
]

4. Using reduce() (Functional and Efficient Approach)

This approach uses reduce() function to iterate over a1 while simultaneously inserting elements from a2 into the accumulator (acc) array in sorted order. The shift() method is used to remove elements from a2 when necessary, ensuring the merged array is sorted.


Output
[
 2, 4, 6, 8, 1,
 2, 3, 4, 5, 6,
 7
]
Comment