function getCombinations(_list) {
var fn = function(active, rest, a) {
if (!active.length && !rest.length)
return;
if (!rest.length) {
a.push(active);
} else {
fn(active.concat(rest[0]), rest.slice(1), a);
fn(active, rest.slice(1), a);
}
return a;
}
return fn([], _list, []);
}
var list = [1, 2, 3, 4]
console.log(getCombinations(list));
它返回一个二维数组,填充了每个组合......
[ [ 1, 2, 3, 4 ]
, [ 1, 2, 3 ]
, [ 1, 2, 4 ]
, [ 1, 2 ]
, [ 1, 3, 4 ]
, [ 1, 3 ]
, [ 1, 4 ]
, [ 1 ]
, [ 2, 3, 4 ]
, [ 2, 3 ]
, [ 2, 4 ]
, [ 2 ]
, [ 3, 4 ]
, [ 3 ]
, [ 4 ]
]
但我想要以下顺序
[ [ 1 ]
, [ 1, 2 ]
, [ 1, 2, 3]
, [ 1, 2, 3, 4 ]
, [ 1, 2, 4]
, [ 1, 3 ]
, [ 1, 3, 4 ]
, [ 1, 4 ]
, [ 2 ]
, ...
, [ 4 ]
]
我尝试使用.sort
,但这会按字母顺序对组合进行排序
getCombinations([ 1, 2, 10 ]).sort()
// [ [ 1 ]
// , [ 1, 10 ]
// , [ 1, 2 ]
// , [ 1, 2, 10 ]
// , [ 10 ]
// , [ 2 ]
// , [ 2, 10 ]
// ]
但这不是我想要的排序。
如何对数组进行排序,以便对数组的内容进行数字处理,并且结果与我上面提到的顺序相同?
最佳答案
您可以使用直接创建所需组合作为排序结果的函数,而不是事后排序。
function getCombinations(list) {
function iter(index, values) {
var temp = values.concat(list[index]);
result.push(temp);
if (++index < list.length) {
iter(index, temp);
iter(index, values);
}
}
var result = [];
iter(0, []);
return result;
}
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
result = getCombinations(list);
console.log(result.length);
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于JavaScript - 按数字方式对二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024556/