javascript - JavaScript - 对二维数组进行数字排序
问题描述
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; }
推荐阅读
- php - 如果未登录,用户将被重定向到“我的帐户”页面。如果已登录,仍然会被重定向。缓存重定向?
- css - 在 Foundation Framework 中使用 rem-calc() 有什么好处?
- django - 在 IIS 上托管 Django REST API 的问题
- css - CSS中的单破折号?这是什么意思?
- amazon-web-services - 连接 AWS EC2 实例以避免 IP 更改连接失败的最佳方式
- airflow - Apache AirFlow:如何在远程机器上安排它
- sql - 如何解决 Access 中的此查询错误?
- python - 如何在 Python3 中沿第三维堆叠两个以上的 numpy 图像数组
- reactjs - `window.location.href` 在 github 页面上部署时不适用于 react 应用程序
- uitableview - 将 UIPanGesture 添加到 UITableView 会阻止 Xcode 11.3 中 UITableView 的滚动