Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Alternatively merging two arrays - 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];
Method 1: Using Index-Based Logic
This approach uses a single loop and alternates between arrays based on even/odd index positions:
const arr1 = [4, 3, 2, 5, 6, 8, 9];
const arr2 = [2, 1, 6, 8, 9, 4, 3];
const mergeAlternatively = (arr1, arr2) => {
const res = [];
for(let i = 0; i
[
4, 2, 3, 1, 2, 6,
5, 8, 6, 9, 8, 4,
9, 3
]
Method 2: Using Two Pointers
This approach uses separate pointers for each array, making the logic clearer:
const mergeAlternativelyTwoPointers = (arr1, arr2) => {
const result = [];
let i = 0, j = 0;
while(i
[
4, 2, 3, 1, 2, 6,
5, 8, 6, 9, 8, 4,
9, 3
]
Handling Different Array Lengths
Both methods handle arrays of different lengths correctly. Here's an example with unequal arrays:
const shortArr = [1, 2];
const longArr = [10, 20, 30, 40, 50];
console.log("Short + Long:", mergeAlternatively(shortArr, longArr));
console.log("Long + Short:", mergeAlternatively(longArr, shortArr));
Short + Long: [ 1, 10, 2, 20, 30, 40, 50 ]
Long + Short: [ 10, 1, 20, 2, 30, 40, 50 ]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Index-based | Medium | Slightly better | Same-length arrays |
| Two pointers | High | Good | Different-length arrays |
Conclusion
Both methods effectively merge arrays alternatively. The two-pointer approach is more readable and intuitive, while the index-based method is more compact for equal-length arrays.
Advertisements
