Given these arrays:
var a = [1, 2, 3];
var b = ['a', 'b', 'c'];
I want to get this result:
[[1, 'a'], [2, 'b'], [3, 'c']];
What’s the best way to do a JavaScript zip to merge arrays like this?
Given these arrays:
var a = [1, 2, 3];
var b = ['a', 'b', 'c'];
I want to get this result:
[[1, 'a'], [2, 'b'], [3, 'c']];
What’s the best way to do a JavaScript zip to merge arrays like this?
The most straightforward way is a for loop iterating through the shortest array length and pairing elements manually:
function zip(arr1, arr2) {
const length = Math.min(arr1.length, arr2.length);
const result = [];
for (let i = 0; i < length; i++) {
result.push([arr1[i], arr2[i]]);
}
return result;
}
console.log(zip(a, b));
If you know both arrays are the same length, you can use .map()
on one array and pair with the corresponding index from the other:
const zipped = a.map((val, idx) => [val, b[idx]]);
console.log(zipped);
Another approach is to use Array.from
with the length of the shortest array, creating the zipped array in a functional style:
const length = Math.min(a.length, b.length);
const zipped = Array.from({ length }, (_, i) => [a[i], b[i]]);
console.log(zipped);
This method is clean, flexible, and works well with dynamic array sizes.