5

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] 
2
  • 2
    does your matrix have a fixed number of lines and columns ? Commented Aug 13, 2018 at 6:54
  • The matrix I'm using is 3x3 in size but for the purposes of this question I would assume that I'm always to use a square matrix (could be 4x4, 5x5). I'll update the question to reflect this. Commented Aug 13, 2018 at 6:56

4 Answers 4

4

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(' '));

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0
var arr1 = [];
var arr2 = [];



for(int i=0; i<mat.length; i++) {
    for(int j=0; j<mat[i].length; j++) {
        arr1.push(mat[i][j]);
    }
}

for(int j=0; j<mat[i].length; j++) {
    for(int i=0; i<mat.length; i++) {
        arr2.push(mat[i][j]);
    }
}

Comments

0

Set a max "width" for your matrix and insert into a new array in loops, offset by 1 for each run.

function transpose(list, width) {
  if (width === void 0) {
    width = 1;
  }
  var t = 0;
  var transposed = [];
  while (t < width) {
    for (var index = t; index < list.length; index += width) {
      transposed.push(list[index]);
    }
    t++;
  }
  return transposed;
}
//TEST
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var transposed = transpose(list, 3);
console.log(list.join());
console.log(transposed.join());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.