比方说,我有一个由数字和数组组成的数组,我想要扁平化它:
[1, [2, [3]] -> [1, 2, 3]很简单。现在,比方说,我想找到所有可能的组合,这样,在任何时候,
[a, [b, c]] -> [[a, b], [a, c]]我正在努力支持这个结构中不可预测的和可能的高复杂度:
[1, [2, [3, 4]], [3, [4, [5, 6]], [7]] -> [[1, 2, 3], [1, 2, 4], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 7]所以这绝对是map/reduce-able的问题,但我就是不能理解它。
发布于 2017-01-30 03:24:53
您可以使用迭代和递归方法,仅当在实际迭代的数组中未找到数组时才收集所有部分并进行推送。
function combine(array) {
var result = [];
array.forEach(function iter(r, p) {
return function (a, _, aa) {
if (Array.isArray(a)) {
a.forEach(iter(r, p + 1));
return;
}
r = r.slice(0, p);
r[p] = a;
aa.some(Array.isArray) || result.push(r);
};
}([], 0));
return result;
}
console.log(combine([1, [2, [3]]])); // [[1, 2, 3]]
console.log(combine(['a', ['b', 'c']])); // [["a", "b"], ["a", "c"]]
console.log(combine([1, [2, [3, 4]], [3, [4, [5, 6]], [7]]])); // [[1, 2, 3], [1, 2, 4], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 7]].as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/41923775
复制相似问题