How to useZip and Unzip in Javascript
By defining the helper functions for zipping and unzipping arrays, after it apply them to transpose the array.
function zip(arrays) {
return arrays[0].map((_, i) => arrays.map(array => array[i]));
}
function transposeArray(arr) {
return zip(arr);
}
const originalArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const transposedArray = transposeArray(originalArray);
console.log("Original Array:");
console.log(originalArray);
console.log("\nTransposed Array:");
console.log(transposedArray);
Output
Original Array: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Transposed Array: [ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]
Transpose a two dimensional (2D) array in JavaScript
Given a 2D array (matrix) and the task is to get the transpose of the matrix using JavaScript.
We can do this by using the following methods:
- Uses the array.map()
- Using the nested loop
- Using reduce() Method
- Using Zip and Unzip