JSFiddle - React, Tailwind, and code Playground

by Matthew Vasallo

JavaScript

// Given two sorted arrays, the task is to merge them in a sorted manner.

// Examples:

// Input :  arr1[] = { 1, 3, 4, 5, 7}  
//          arr2[] = {2, 4, 6, 8}
// Output : arr3[] = {1, 2, 3, 4, 5, 6, 7, 8}

// Input  : arr1[] = { 5, 8, 9}  
//          arr2[] = {4, 7, 8}
// Output : arr3[] = {4, 5, 7, 8, 8, 9}

//Can you see me typing?

const arr1 = [1, 2, 5, 7, 9];
const arr2 = [3, 4, 6, 8];

const mergeArrays = (arr1, arr2) => {
    let resultArray = [];
    let i = 0;
    let j = 0;
    while(i<arr1.length && j<arr2.length){
        if(arr1[i] < arr2[j]){
            resultArray.push(arr1[i]);
            i++;
        }
        else{
            resultArray.push(arr2[j]);
            j++;
        }
    }
        if(i < arr1.length){
            while (i < arr1.length) {
             resultArray.push(arr1[i]);
             i++;
         }
        }
        else if(j < arr2.length){
            while (j < arr2.length) {
             resultArray.push(arr2[j]);
             j++;
         }
        }
    
    return resultArray;
};

console.log(mergeArrays(arr1, arr2));