My question is closely related to this question but I'm looking for a solution in Javascript
How to Transpose 2D Matrix Stored as C 1D Array
Basically I have a 2D square matrix
1 2 3
4 5 6
7 8 9
Stored as follows
let anArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9]
How can I transpose this matrix so that the elements of my source array are switched as follows?
let newArray = [1, 4, 7, 2, 5, 8, 3, 6, 9]
Transpose of a two-dimensional array - JavaScript 1 Transpose. The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). 2 Example 3 Output
The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). We can transpose a matrix (2-D array) by switching its rows with its columns.
1 Transpose. The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). 2 Example 3 Output
axes: By default the value is None. When None or no value is passed it will reverse the dimensions of array arr. The axes parameter takes a list of integers as the value to permute the given array arr. The transpose of the 1-D array is the same. The output of the transpose () function on the 1-D array does not change.
You could take the length for the dimension of the array and map items on a specific index for a new array.
var array = [1 ,2, 3, 4, 5, 6, 7, 8, 9],
n = Math.sqrt(array.length),
transposed = array.map((_, i, a) => a[(i % n) * n + Math.floor(i / n)]);
console.log(transposed.join(' '));
The approach in the answer you linked to works well in JavaScript too.
For a 3 x 3:
const anArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArray = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
newArray[3 * i + j] = anArray[3 * j + i];
}
}
console.log(newArray);
For an N x N, just replace the 3's with N.
This answer avoids division and flooring (integer division) and a decent optimizer should make the code relatively fast. You might also consider initializing the new array with
let newArray = new Array(9);
or
let newArray = new Array(N * N);
but profile the code before attempting "optimizations" such as this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With