对矩阵中的列进行排序

Bel*_*dar -1 javascript sorting matrix lodash

我有一个非唯一值的矩阵(或多维数组),如下所示:

var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]
Run Code Online (Sandbox Code Playgroud)

我想对这个矩阵的一行进行排序,但是其他行应该重新排序,以保持列像组织一样.

//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我更喜欢lodash解决方案.

Nin*_*olz 5

您可以使用带索引的数组,并使用值对其进行排序matrix[0].然后使用已排序的元素构建一个新数组.

var matrix = [[1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4]],
    indices = matrix[0].map((_, i) => i);

indices.sort((a, b) => matrix[0][a] - matrix[0][b]);

result = matrix.map(a => indices.map(i => a[i]));

console.log(result);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)