
- 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 arrays in a unique way in JavaScript
We are required to write a JavaScript function that takes in two arrays and merges the arrays taking elements alternatively from the arrays.
For example
If the two arrays are −
const arr1 = [4, 3, 2, 5, 6, 8, 9]; const arr2 = [2, 1, 6, 8, 9, 4, 3];
Then the output should be −
const output = [4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3];
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr1 = [4, 3, 2, 5, 6, 8, 9]; const arr2 = [2, 1, 6, 8, 9, 4, 3]; const mergeAlernatively = (arr1, arr2) => { const res = []; for(let i = 0; i < arr1.length + arr2.length; i++){ if(i % 2 === 0){ res.push(arr1[i/2]); }else{ res.push(arr2[(i-1)/2]); }; }; return res; }; console.log(mergeAlernatively(arr1, arr2));
Output
The output in the console will be −
[ 4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3 ]
- Related Articles
- Alternatively merging two arrays - JavaScript
- Merging and rectifying arrays in JavaScript
- Merging sorted arrays together JavaScript
- Merging two sorted arrays into one sorted array using JavaScript
- Merging two unsorted arrays in sorted order in C++.
- Merging Arrays in Perl
- Merging nested arrays to form 1-d array in JavaScript
- Unique intersection of arrays in JavaScript
- Merging elements of two different arrays alternatively in third array in C++.
- Maximizing Unique Pairs from two arrays in C++
- Merging subarrays in JavaScript
- The easiest way to concatenate two arrays in PHP?
- Quickly merging two sorted arrays using std::merge() in C++ STL(cute ho ap)
- Deviations in two JavaScript arrays in JavaScript
- Getting unique values within two arrays in one MongoDB document

Advertisements