issue with merge sorted arrays problem using javascript

I am trying to solve merge 2 sorted arrays problem using javascript. Please find my solution below:

input:

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

output:

[1, 2, 3, 4, 7, 8, 9 10]

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

let arrayItem1 = arr1[0];
let arrayItem2 = arr2[0];
let i = 1;
let j = 1;
let mergedArray = [];

while(arrayItem2 || arrayItem1) {

    arrayItem1 = arrayItem1 === undefined ? 0 : arrayItem1;
  arrayItem2 = arrayItem2 === undefined ? 0 : arrayItem2;
    if (arrayItem1 < arrayItem2) {
        console.log('inside if');
        console.log("first array", arrayItem1);
        arrayItem1 = arr1[i];
        i++;    
        mergedArray.push(arrayItem1);
      } else {
        console.log('inside else');
        console.log("second array", arrayItem2);
        arrayItem2 = arr2[j];
        j++;    
        mergedArray.push(arrayItem2);
      }
  
  console.log("== merged array ==", mergedArray);
}

But it is going in infinite loop. Not sure where I am going wrong. Need a watchful pair of eyes here.

thanks

10 thoughts on “issue with merge sorted arrays problem using javascript”

Leave a Comment