我有一个非唯一值的矩阵(或多维数组),如下所示:
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解决方案。
使用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));
您可以使用带索引的数组,并使用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; }