对矩阵中的列进行排序

问题描述 投票:-1回答:2

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

var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]

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

//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]

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

javascript sorting matrix lodash
2个回答
3
投票

使用lodash你可以用zip转置矩阵,用给定的sortBy数字用row对它进行排序,然后将其转置回来:

_.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row))

var matrix = [
    [1, 3, 2, 4, 1],
    [2, 4, 1, 3, 2],
    [4, 3, 2, 1, 4]
];
var row = 0;

result = _.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row));

console.log(result.join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

使用rest parameter syntax,你也可以这样写:

_.zip(..._.sortBy(_.zip(...matrix), row));

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.