在javascript中使用矩阵的列(换位)交换行

Bak*_*yor 25 javascript swap matrix multidimensional-array

例如,我有一个像这样的矩阵:

|1 2 3|    
|4 5 6|
|7 8 9|
Run Code Online (Sandbox Code Playgroud)

我需要它转换成这样的矩阵:

|1 4 7|    
|2 5 8|
|3 6 9|
Run Code Online (Sandbox Code Playgroud)

实现这一目标的最佳和最佳方式是什么?

hob*_*obs 60

谷歌搜索出现了这个.令人惊讶的是,它比尼基塔答案更加简洁和完整.它在内核中隐式检索列和行长度map().

function transpose(a) {
    return Object.keys(a[0]).map(function(c) {
        return a.map(function(r) { return r[c]; });
    });
}

console.log(transpose([
    [1,2,3],
    [4,5,6],
    [7,8,9]
]));
Run Code Online (Sandbox Code Playgroud)

  • IEX <9不支持Object.keys,所以在这种情况下,如果你需要提供支持,我会坚持其他一个答案. (4认同)
  • 虽然这里有一个详细的修复程序... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys (3认同)

tro*_*ynt 17

参见文章:在JavaScript和jQuery中转置数组

function transpose(a) {

  // Calculate the width and height of the Array
  var w = a.length || 0;
  var h = a[0] instanceof Array ? a[0].length : 0;

  // In case it is a zero matrix, no transpose routine needed.
  if(h === 0 || w === 0) { return []; }

  /**
   * @var {Number} i Counter
   * @var {Number} j Counter
   * @var {Array} t Transposed data is stored in this array.
   */
  var i, j, t = [];

  // Loop through every item in the outer array (height)
  for(i=0; i<h; i++) {

    // Insert a new row (array)
    t[i] = [];

    // Loop through every item per item in outer array (width)
    for(j=0; j<w; j++) {

      // Save transposed data.
      t[i][j] = a[j][i];
    }
  }

  return t;
}

console.log(transpose([[1,2,3],[4,5,6],[7,8,9]]));
Run Code Online (Sandbox Code Playgroud)


Nik*_*bak 7

就像任何其他语言一样:

int[][] copy = new int[columns][rows];
for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < columns; ++j) {
        copy[j][i] = original[i][j];
    }
}
Run Code Online (Sandbox Code Playgroud)

您只需在JS中以不同方式构造2D数组.像这样:

function transpose(original) {
    var copy = [];
    for (var i = 0; i < original.length; ++i) {
        for (var j = 0; j < original[i].length; ++j) {
            // skip undefined values to preserve sparse array
            if (original[i][j] === undefined) continue;
            // create row if it doesn't exist yet
            if (copy[j] === undefined) copy[j] = [];
            // swap the x and y coords for the copy
            copy[j][i] = original[i][j];
        }
    }
    return copy;
}

console.log(transpose([
    [1,2,3],
    [4,5,6],
    [7,8,9]
]));
Run Code Online (Sandbox Code Playgroud)


小智 5

我没有足够的声誉来评论(wtf.),所以我需要将Ken的更新版本作为单独的答案发布:

function transpose(a) {
    return a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); });
}
Run Code Online (Sandbox Code Playgroud)