将嵌套数组元素转换为字符串数组

给定一个简单的嵌套数组数组,如下所示:


[

  ['a','b',],

  ['c','d'],

  ['e']

]

我希望连接每个元素的值并创建一个这样的数组:


['.a.c.e','.a.d.e','.b.c.e','.b.d.e']

这只是一个简单的例子,但实际上可能有 3 个以上的嵌套数组和任意数量的元素。


看起来它应该相对简单,但我就是无法解决它,任何人都可以帮忙吗?


阿晨1998
浏览 147回答 1
1回答

幕布斯6054654

由于数组长度未知,最好的方法是使用递归: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)), [""]))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript