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
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 ?
[4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3]
Using Index-Based Approach
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 mergeAlternatively = (arr1, arr2) => {
const res = [];
for(let i = 0; i
[
4, 2, 3, 1, 2, 6,
5, 8, 6, 9, 8, 4,
9, 3
]
Using Math.max() for Different Array Lengths
Here's an approach that handles arrays of different lengths better:
const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8, 9, 10];
const mergeAlternatively = (arr1, arr2) => {
const res = [];
const maxLength = Math.max(arr1.length, arr2.length);
for(let i = 0; i
[1, 5, 2, 6, 3, 7, 4, 8, 9, 10]
How It Works
The first approach uses modulo operator to determine which array to pick from:
- Even indices (0, 2, 4...) take from arr1 at positions (0, 1, 2...)
- Odd indices (1, 3, 5...) take from arr2 at positions (0, 1, 2...)
The second approach iterates through both arrays simultaneously, adding elements when available.
Comparison
| Method | Handles Different Lengths? | Complexity |
|---|---|---|
| Index-based | Limited | Simple logic |
| Math.max approach | Yes | More flexible |
Conclusion
Both approaches merge arrays alternately. Use the Math.max method for arrays of different lengths, or the index-based approach for equal-length arrays with simpler logic.
Advertisements
