Sign in

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++;
}
}

Olivia Z

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store