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.

JavaScript
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:

Similar Reads

Approach 1: Uses the array.map()

Store a 2D array into a variable.Display the 2D array (matrix) content.Call map() method which provides a callback function single time for every element in an array, maintaining the order and returns a new array (transpose of the original array) from the results....

Approach 2: Using the nested loop

Store a 2D array into a variable.Replace every element in the array with its mirror image with respect to the diagonal of the array....

Approach 3: Using reduce() Method

We can use reduce() method and map() for transposing the array....

Approach 4: Using Zip and Unzip

By defining the helper functions for zipping and unzipping arrays, after it apply them to transpose the array....

Contact Us