Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge two sorted arrays to form a resultant sorted array in JavaScript
We are required to write a JavaScript function that takes in two sorted array of numbers. The function should merge the two arrays together to form a resultant sorted array and return that array.
For example −
If the two arrays are −
const arr1 = [2, 6, 6, 8, 9]; const arr2 = [1, 4, 5, 7];
Then the output array should be −
const output = [1, 2, 4, 6, 6, 7, 8, 9];
Example
The code for this will be −
const arr1 = [2, 6, 6, 8, 9];
const arr2 = [1, 4, 5, 7];
const mergeSortedArrays = (arr1 = [], arr2 = []) => {
let m = arr1.length;
let n = arr2.length;
let currentIndex = m + n;
const checkNum1HasLargerNumber = (a, b) => {
if (a < 0) {
return false;
};
if (b < 0) {
return true;
};
return arr1[a] >= arr2[b];
};
m −= 1;
n −= 1;
while (currentIndex−−) {
let hasNums1LargerNumber = checkNum1HasLargerNumber(m, n);
arr1[currentIndex] = hasNums1LargerNumber ? arr1[m] : arr2[n];
if (hasNums1LargerNumber) {
m −= 1;
} else {
n −= 1;
}
};
};
mergeSortedArrays(arr1, arr2);
console.log(arr1);
Output
And the output in the console will be −
[ 1, 2, 4, 5, 6, 6, 7, 8, 9 ]
Advertisements