JavaScript Data Structures-Merge Two Sorted Arrays

Olivia Z
1 min readMay 21, 2021

If you would like to merged two sorted arrays, how many methods we can use to solve the problem. There are two ways one a brute force way and a more efficient way. For the more traditional way is to create a new array and then compare each element in each two sorted arrays and append it to the new array. And the simple way is to use the spread operator and sort method in JavaScript.

First method:

function mergedTwoArrays(arr1,arr2){
let mergedArray= [];
let i = 0, j=0;
while((i < arr1.length)&&(j< arr2.length)){
if(arr1[i]<arr2[j]){
mergedArray.push(arr1[i]);
i++;
}else{
mergedArray.push(arr2[j]);
j++;
}
}
if(i<=(arr1.length-1)){
arr1.splice(0,i);
mergedArray=mergedArray.concat(arr1);
}else if(j<=(arr2.length-1)){
arr2.splice(0,j);
mergedArray=mergedArray.concat(arr2);
}
return mergedArray;}

For the time complexity is O(m+n), where m and n is number of elements in arr1 and arr2.

Second method:

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

For the time complexity is O(nlogn), we are using sort in here.

--

--