# Merge two sorted array

Posted on Oct - 2019

### Given two sorted array , merge and create sorted array out of it. i.e

Input: array1 = [0,3,4,31]

Input: array2 = [9,11,17,21]

Expected result = [0,3,4,9,11,17,21,31]

Let's implement the code using javascript

``````const mergeSortedArray = (arr1, arr2) => {

let mergedArray = [];

// edge case 1 if arr1 is empty then return arr2
if(arr1.length === 0){
return arr2;
}
// edge case 2 if arr2 is empty then return arr1
if(arr2.length === 0){
return arr1;
}

// two counter for maintaining the index of the arrays
let i =1 , j = 1;

let arr1item = arr1, arr2item = arr2;

//need to continue the loop till the item exits in any of the array
while(arr1item || arr2item){

if(!arr2item || arr1item < arr2item){
mergedArray.push(arr1item);
arr1item = arr1[i];
i++;
}else{
mergedArray.push(arr2item);
arr2item = arr2[j];
j++;
}

}
return mergedArray;

}

module.exports = mergeSortedArray
``````

Here we are using javascript as the language and node.js as a platform or environment to execute the code.

We will use jest as testing framework to run the test cases to verify the algorithm. For using jest you can install jest as global depedency for running the test.

npm install -g jest

``````const mergeSortedArray = require('./merge2sortedarray');

test('marged array result both array size equal', () => {
expect(mergeSortedArray([0,3,4,31],[9,11,17,21])).toStrictEqual([0,3,4,9,11,17,21,31]);
});

test('marged array result arr1 empty', () => {
expect(mergeSortedArray([],[9,11,17,21])).toStrictEqual([9,11,17,21]);
});

test('marged array result arr2 empty', () => {
expect(mergeSortedArray([0,3,4,31],[])).toStrictEqual([0,3,4,31]);
});

test('marged array result eunequal array', () => {
expect(mergeSortedArray([0,3,4,31],[9,11])).toStrictEqual([0,3,4,9,11,31]);
});``````

Create a file named test.js and run the below command from your command line to check the test cases.

jest

#### Categories

 CSS Java AngularJS Groovy Grails JavaScript MongoDB React-redux SQL