【问题标题】:searching an item that has an array of items and so on node.js搜索具有项目数组的项目等 node.js
【发布时间】:2019-04-07 14:08:14
【问题描述】:

想象一下,我有一个 Item,它有一个 Items 数组,并且 Array 中的任何 Items 都有一个 Items 数组,依此类推。 所以我有无限级别的项目,我想知道如何在 node.js 中访问所有项目。 像这样:

    Item1
     /     \
   Item2    Item3
            /    \
          Item4   Item5

Item1 是一个数组。 Item2 和 Item3 另一个数组等等。

【问题讨论】:

  • 你会发现我们没有那么大的想象力。 :-) 也许向我们展示更多你想要做的事情?
  • 签出this
  • 我已经用图表进行了编辑。

标签: arrays node.js recursion


【解决方案1】:

我有一个包含一系列项目的项目...我想知道如何获取所有项目

如果是数组,则递归展平数组中的每个元素,否则追加。

/* setup test input */
const tree = [
  "leaf_A_1",
  "leaf_A_2",
  [
    "leaf_B_1",
    "leaf_B_2",
    [
      "leaf_C_1",
      "leaf_C_2",
    ]
  ]
]
console.log("INPUT:\n", tree)

/* run test */
const leaves = flatten(tree)
console.log("OUTPUT:", leaves) // outputs leaf nodes in a flat array

// flatten() is a recursive function takes an array that *may* contain nested arrays, and returns an array containing all leaf elements without nesting.
function flatten(arr) {
  return arr.reduce(expandNestedArraysOrAppend, [])
}

function expandNestedArraysOrAppend(accum, element, idx) {
  if (Array.isArray(element)) {
    return [...accum, ...flatten(element)] // if we have an array, flatten it before appending
  }
  return [...accum, element]               // if not an array, just append
}

希望这会有所帮助。干杯!

【讨论】:

    猜你喜欢
    • 2016-06-20
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2019-03-18
    • 1970-01-01
    • 2020-04-27
    • 2013-11-01
    相关资源
    最近更新 更多