Javascript 用javascript中的矩阵的列(转置)交换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4492678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:38:12  来源:igfitidea点击:

Swap rows with columns (transposition) of a matrix in javascript

javascriptmatrixmultidimensional-arrayswap

提问by Bakhtiyor

For instance I have a matrix like this:

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

|1 2 3|    
|4 5 6|
|7 8 9|

and I need it to convert into a matrix like this:

我需要将其转换为这样的矩阵:

|1 4 7|    
|2 5 8|
|3 6 9|

What is the best and optimal way to achieve this goal?

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

采纳答案by troynt

See article: Transpose An Array In JavaScript and jQuery

请参阅文章:在 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]]));

回答by hobs

DuckDuckingturned up thisby Ken. Surprisingly, it's even more concise and complete than Nikita's answer. It retrieves column and row lengths implicitly within the guts of map().

DuckDucking打开了这个。令人惊讶的是,它比Nikita回答更简洁和完整。它在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]
]));

[[1,4,5],[2,5,8],[7,8,9]

[[1,4,5],[2,5,8],[7,8,9]

回答by Nikita Rybak

Just like in any other language:

就像在任何其他语言中一样:

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];
    }
}

You just have to construct the 2D array differently in JS. Like this:

你只需要在 JS 中以不同的方式构造二维数组。像这样:

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]
]));

回答by KIT-Inwi

I don't have enough reputation to comment (wtf.), so I need to post Ken's updated versionas a separate answer:

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

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

回答by Anton Iokov

Compact version of Hobs' answerusing arrow functions from ES6:

使用 ES6 中的箭头函数的 Hobs答案的紧凑版本:

function transpose(matrix) {
    return Object.keys(matrix[0])
        .map(colNumber => matrix.map(rowNumber => rowNumber[colNumber]));
}

回答by Pedro Justo

You can use Object.keysand Array.prototype.map:

您可以使用Object.keysArray.prototype.map

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

console.log(transpose([
    [1,2,3],
    [4,5,6],
    [7,8,9]
]));