
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ]
- Related Articles
- Merge two sorted arrays in Java
- Merge two sorted arrays in C#
- Merge two sorted arrays using C++.
- Merging two sorted arrays into one sorted array using JavaScript
- Program to merge two sorted list to form larger sorted list in Python
- Merge two sorted arrays in Python using heapq?
- Merge two sorted arrays into a list using C#
- C# program to merge two sorted arrays into one
- Merge k sorted arrays in Java
- Merge Sorted Array in Python
- Merge Two Sorted Lists in Python
- Merge k sorted arrays of different sizes in C++
- Merging sorted arrays together JavaScript
- Java program to create a sorted merged array of two unsorted arrays
- Quickly merging two sorted arrays using std::merge() in C++ STL(cute ho ap)

Advertisements