# Blog

## JavaScript Merge Function that Mergers Two Arrays Already Sorted from Lowest to Highest Numbers Posted on July 15, 2015 in Algorithms, JavaScript by Matt Jennings

```// Function merges 2 arrays that are already sort from
// Lowest to highest numbers
function mergeSortedArrays(arr1, arr2) {

// Empty array that will have rules from 2 arrays
// pushed into it
var result = [];

// Length of "result" array that will have
// values pushed into
var i = arr1.length + arr2.length - 1;

// Iterate over the entire length of
// arrays "arr1" and "arr2", even if there aren't the same length
// and the interation continues until "arr1" and/or "arr2"
// don't have any more elements
while(arr1.length || arr2.length) {
// If the same element index from "arr1" is greater than
// the same element index from "arr2" pop off that element
// from "arr1" and assign it to the last "result" element
// and decrement by 1
if(arr1[arr1.length - 1] > arr2[arr2.length - 1]) {
result[i--] = arr1.pop();
}
// Else the same element index from "arr2" is greater than
// the same element index from "arr1" pop off that element
// from "arr2" and assign it to the last "result" element
// and decrement by 1
else {
result[i--] = arr2.pop();
}
}

// If there are any remaing element from "arr1",
// because it doesn't have the same elements as "arr2",
// pop off the final element of "arr1" and assign it to
// the "result" array and after that decrement by 1
while(arr1.length) {
result[i--] = arr1.pop();
}

// If there are any remaing element from "arr2",
// because it doesn't have the same elements as "arr1",
// pop off the final element of "arr1" and assign it to
// the "result" array and after that decrement by 1
while(arr2.length) {
result[i--] = arr2.pop();
}

console.log("arr1 elements:", arr1);
console.log("arr2 elements:", arr2);
console.log("result array elements:", result);

}

var array1 = [1, 2, 5, 9];

var array2 = [-9, 4, 8, 15, 20];

/*
JS console output:
"arr1 elements:"
[]
"arr2 elements:"
[]
"result array elements:"
[-9, 1, 2, 4, 5, 8, 9, 15, 20]
*/
mergeSortedArrays(array1, array2);```