Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript- Merge two Sorted Arrays
Next article icon

JavaScript- Merge two Sorted Arrays

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following ways to merge two sorted arrays:

1. Using Two Pointers (Efficient For Large Arrays)

This approach involves using two pointers, one for each array, and comparing their elements as you iterate through them. This method works efficiently in O(n + m) time, where n and m are the lengths of the two arrays.

JavaScript
function fun(a1, a2) {     let i = 0, j = 0, res = [];      while (i < a1.length && j < a2.length) {         if (a1[i] < a2[j]) {             res.push(a1[i]);             i++;         } else {             res.push(a2[j]);             j++;         }     }      // If any elements remain in a1 or a2, add them to the res     while (i < a1.length) {         res.push(a1[i]);         i++;     }      while (j < a2.length) {         res.push(a2[j]);         j++;     }      return res; }  const a1 = [1, 3, 5, 7]; const a2 = [2, 4, 6, 8];  console.log(fun(a1, a2)); 

Output
[   1, 2, 3, 4,   5, 6, 7, 8 ] 

2. Using concat() and sort() (Less Efficient)

You can merge both arrays using concat() and then use sort() to sort the merged array. However, this method has a time complexity of O((n + m) * log(n + m)), where n and m are the lengths of the arrays, due to the sorting step.

JavaScript
const a1 = [1, 3, 5, 7]; const a2 = [2, 4, 6, 8]; let res =  a1.concat(a2).sort((a, b) => a - b);  console.log(res); 

Output
[   1, 2, 3, 4,   5, 6, 7, 8 ] 

3. Using push() in a Loop (Manual Merge and Less Efficient)

This approach manually merges the arrays using push() without explicitly using two pointers or the sort() function. It iterates through both arrays and adds the elements in sorted order.

JavaScript
const a1 = [1, 3, 5, 7]; const a2 = [2, 4, 6, 8]; let res = [];  while (a1.length || a2.length) {     if (!a1.length) {         res.push(a2.shift());     } else if (!a2.length) {         res.push(a1.shift());     } else if (a1[0] < a2[0]) {         res.push(a1.shift());     } else {         res.push(a2.shift());     } } console.log(res); 

Output
[   1, 2, 3, 4,   5, 6, 7, 8 ] 

4. Using reduce() (Functional and Efficient Approach)

This approach uses reduce() function to iterate over a1 while simultaneously inserting elements from a2 into the accumulator (acc) array in sorted order. The shift() method is used to remove elements from a2 when necessary, ensuring the merged array is sorted.

JavaScript
function fun(a1, a2) {     return a1.reduce((acc, val) => {         while (a2.length && a2[0] <= val) {             acc.push(a2.shift());         }         acc.push(val);         return acc;     }, [...a2]); }  const a1 = [1, 3, 5, 7]; const a2 = [2, 4, 6, 8];  console.log(fun(a1, a2)); 

Output
[   2, 4, 6, 8, 1,   2, 3, 4, 5, 6,   7 ] 

Next Article
JavaScript- Merge two Sorted Arrays

M

meetahaloyx4
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array

Similar Reads

    Javascript Program to Merge 3 Sorted Arrays
    Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D. Examples: Input : A = [1, 2, 3, 4, 5] B = [2, 3, 4] C = [4, 5, 6, 7] Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7] Input : A = [1, 2, 3, 5] B = [6, 7, 8
    8 min read
    Merge K Sorted Array using JavaScript
    We are given K sorted arrays and our task is to merge them into a single sorted array in JavaScript.Example:Input: arrays = [[2, 4, 5], [1, 3, 8], [0, 7, 9]];Output: [0, 1, 2, 3, 4, 5, 7, 8]These are the following approaches:Table of ContentNaive ApproachDivide and Conquer ApproachMin-Heap ApproachN
    5 min read
    Find Kth Element of Two Sorted Arrays in JavaScript
    Given two sorted arrays, our task is to find the Kth element in the combined array made by merging the two input arrays in JavaScript.Example:Input: Arr1: [1, 2, 5] , Arr2:[2, 4, 6, 8], K = 4Output: Kth element is 4.Explanation:The final Array would be: [1, 2, 2, 4, 5, 6, 8]The 4th element of this a
    3 min read
    Javascript Program To Merge Two Sorted Lists (In-Place)
    Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples:Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9Explanation: The output list is in sorted order.Input: head1: 1->3->5->7 head2: 2->4Outp
    5 min read
    Javascript Program to Print uncommon elements from two sorted arrays
    Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples :Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50}Output : 10 25 40 50We do not print 20 and 30 as theseelements are pr
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences