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
Combining two arrays in JavaScript
In JavaScript, combining two arrays means pairing corresponding elements from each array to create a new array of subarrays. This is commonly known as "zipping" arrays together.
For example, if we have two arrays of the same length, we can combine their elements at matching indices to form pairs.
If the two arrays are:
const arr1 = ['a', 'b', 'c']; const arr2 = [1, 2, 3];
Then the expected output should be:
[
['a', 1],
['b', 2],
['c', 3]
]
Using a for Loop
The most straightforward approach is to iterate through both arrays simultaneously using a for loop:
const arr1 = ['a', 'b', 'c'];
const arr2 = [1, 2, 3];
const combineCorresponding = (arr1 = [], arr2 = []) => {
const res = [];
for(let i = 0; i < arr1.length; i++){
const el1 = arr1[i];
const el2 = arr2[i];
res.push([el1, el2]);
}
return res;
};
console.log(combineCorresponding(arr1, arr2));
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
Using map() Method
A more functional approach uses the map() method to transform one array while accessing the corresponding elements from the second array:
const arr1 = ['a', 'b', 'c'];
const arr2 = [1, 2, 3];
const combineWithMap = (arr1, arr2) => {
return arr1.map((element, index) => [element, arr2[index]]);
};
console.log(combineWithMap(arr1, arr2));
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
Handling Arrays of Different Lengths
When arrays have different lengths, we should handle the shorter array gracefully:
const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = [1, 2, 3];
const combineWithCheck = (arr1, arr2) => {
const minLength = Math.min(arr1.length, arr2.length);
const result = [];
for(let i = 0; i < minLength; i++){
result.push([arr1[i], arr2[i]]);
}
return result;
};
console.log(combineWithCheck(arr1, arr2));
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
Comparison
| Method | Readability | Performance | Handles Different Lengths |
|---|---|---|---|
| for loop | Good | Fast | With modification |
| map() | Excellent | Good | With modification |
Conclusion
Both approaches work well for combining arrays. Use map() for cleaner, functional code, or a for loop for maximum performance and explicit control over the iteration process.
