- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements