【问题标题】:Converting nested array elements to array of strings [duplicate]将嵌套数组元素转换为字符串数组[重复]
【发布时间】:2019-10-24 08:34:38
【问题描述】:

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

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

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

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

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

看起来应该比较简单,但我就是想不通,谁能帮忙?

【问题讨论】:

  • 尚不清楚您的输入数组与预期输出的关系。您能否扩展您正在尝试做的事情
  • 我基本上是在尝试构建一个 jquery 类选择器,其中输出具有输入值的每个组合。所以你可以在我的问题中看到,有 2 x 2 x 1 种可能的组合,所以有 4 个结果。显然,如果每个数组中有更多元素或更多数组,就会有更多可能的组合。我基本上需要一个包含所有可能组合的数组

标签: javascript


【解决方案1】:

由于数组长度未知,最好的办法是使用递归:

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)), [""])
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-11
    • 2021-04-07
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多