1 回答
TA贡献1876条经验 获得超7个赞
由于数组长度未知,最好的方法是使用递归:
function conc(input) {
const output = [];
function _conc(input, partial) {
if (input.length === 0) {
return output.push(partial);
}
const [first, ...rest] = input;
first.forEach(itm => {
_conc(rest, partial + "." + itm)
});
}
_conc(input, "");
return output;
}
const input = [
['a','b',],
['c','d'],
['e']
]
console.log(conc(input))
或与flatMap:
function conc(input) {
const [first, ...rest] = input;
return rest.length === 0
? first.map(itm => "." + itm)
: first.flatMap(itm => conc(rest).map(_itm => "." + itm + _itm));
}
const input = [
['a','b',],
['c','d'],
['e']
]
console.log(conc(input))
或减少:
const input = [
['a','b',],
['c','d'],
['e']
]
console.log(
input.reduce((acc, a) => acc.flatMap(i1 => a.map(i2 => i1 + "." + i2)), [""])
)
添加回答
举报