Suppose we have two sorted arrays (increasing order) like this −
const arr1 = [1, 2, 3, 0, 0, 0]; const arr2 = [2, 5, 6];
We are required to write a JavaScript function that takes in two such arrays and returns a new array that contains all the elements from these arrays in a sorted manner.
Therefore, for the above arrays, the output should look like −
const output = [1, 2, 2, 3, 5, 6];
Example
const arr1 = [1, 2, 3, 0, 0, 0]; const arr2 = [2, 5, 6]; const mergeSortedArrays = (arr1, arr2) => { let { length: l1 } = arr1; let { length: l2 } = arr2; while(l2){ arr1[l1++] = arr2[--l2]; }; const sorter = (a, b) => a - b; arr1.sort(sorter); }; mergeSortedArrays(arr1, arr2); console.log(arr1);
Output
And the output in the console will be −
[ 0, 0, 0, 1, 2, 2, 3, 5, 6 ]