
- 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
Merging two sorted arrays into one sorted array using JavaScript
Problem
We are required to write a JavaScript function that takes in two sorted arrays of numbers our function should merge all the elements of both the arrays into a new array and return that new array sorted in the same order.
Example
Following is the code −
const arr1 = [1, 3, 4, 5, 6, 8]; const arr2 = [4, 6, 8, 9, 11]; const mergeSortedArrays = (arr1 = [], arr2 = []) => { const res = []; let i = 0; let j = 0; while(i < arr1.length && j < arr2.length){ if(arr1[i] < arr2[j]){ res.push(arr1[i]); i++; }else{ res.push(arr2[j]); j++; } }; while(i < arr1.length){ res.push(arr1[i]); i++; }; while(j < arr2.length){ res.push(arr2[j]); j++; }; return res; }; console.log(mergeSortedArrays(arr1, arr2));
Output
[ 1, 3, 4, 4, 5, 6, 6, 8, 8, 9, 11 ]
- Related Articles
- Merging sorted arrays together JavaScript
- Merging two unsorted arrays in sorted order in C++.
- C# program to merge two sorted arrays into one
- Merge two sorted arrays to form a resultant sorted array in JavaScript
- Merge two sorted arrays into a list using C#
- Quickly merging two sorted arrays using std::merge() in C++ STL(cute ho ap)
- Merge two sorted arrays using C++.
- Merge two sorted arrays in Python using heapq?
- Alternatively merging two arrays - JavaScript
- Merge two sorted arrays in Java
- Merge two sorted arrays in C#
- JavaScript Program for find common elements in two sorted arrays
- Print uncommon elements from two sorted arrays
- Median of Two Sorted Arrays in C++
- Intersection of three sorted arrays in JavaScript

Advertisements