我有一个数组:
[
[3, 1],
[3, 3],
[2, 2],
[0, 0],
[1, 3]
]
当我按(i [0] + i [1])对数组进行排序时,我得到了:
[
[3, 3],
[3, 1],
[2, 2],
[1, 3],
[0, 0]
]
我想从此数组中获取前2个元素,但是正如您所看到的,b / w实际上没有区别[3,1],[2,2]和[1,3]。 [3,1]被排序为2nd的唯一原因是它在原始数组中的索引较小。因此,我希望进行所有可能的排序(在这种情况下为6个数组),每个排序在第二位具有不同的项。
我如何做到这一点?
编辑:
排序功能:
(a,b) => (b[0]+b[1]) - (a[0]+a[1]));
预期输出:
[
[
[3, 3],
[3, 1],
[2, 2],
[1, 3],
[0, 0]
],
[
[3, 3],
[3, 1],
[1, 3],
[2, 2],
[0, 0]
],
[
[3, 3],
[2, 2],
[1, 3],
[3, 1],
[0, 0]
],
[
[3, 3],
[2, 2],
[3, 1],
[1, 3],
[0, 0]
],
[
[3, 3],
[1, 3],
[2, 2],
[3, 1],
[0, 0]
],
[
[3, 3],
[1, 3],
[3, 1],
[2, 2],
[0, 0]
],
]
答案 0 :(得分:2)
您可以
function permutation(array) {
function p(array, temp) {
var i, x;
if (!array.length) {
result.push(temp);
}
for (i = 0; i < array.length; i++) {
x = array.splice(i, 1)[0];
p(array, temp.concat([x]));
array.splice(i, 0, x);
}
}
var result = [];
p(array, []);
return result;
}
function cartesian(array) {
function c(part, index) {
array[index].forEach(function (a) {
var p = part.concat([a]);
if (p.length === array.length) {
return r.push(p);
}
c(p, index + 1);
});
}
var r = [];
c([], 0);
return r;
}
var array = [[3, 1], [3, 3], [2, 2], [0, 0], [1, 3]],
groups = Object
.values(array.reduce(
(r, a) => ((r[a[0] + a[1]] = r[a[0] + a[1]] || []).push(a), r),
Object.create(null)
))
.reverse()
.map(permutation),
result = cartesian(groups).map(c => c.reduce((a, b) => a.concat(b), []));
console.log(result.map(a => a.map(b => b.join())));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }