arrays - 搜索包含项目数组的项目等node.js

标签 arrays node.js recursion

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

    Item1
     /     \
   Item2    Item3
            /    \
          Item4   Item5

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

最佳答案

I have an Item that has an array of Items ... i want to know how to get to all of them

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

/* 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
}

希望这有帮助。干杯!

关于arrays - 搜索包含项目数组的项目等node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53133664/

相关文章:

javascript - 如何计算递归函数的复杂度?

c - 仅使用递归如何实现 O(log n) 幂函数 a^n ?

hadoop - 如何在新的 Hadoop API 中递归使用目录结构?

c# - 从字符串数组中删除列表中的内容

c# - x 数组中的重复元素添加到 y 数组中

node.js - 通过 google http rest api 发送电子邮件

arrays - Node.JS + MongoDB 聚合 从 MongoDB 中的数据库中查找数组中的数组

javascript - 某些元素未从数组中删除

php - 在不知道行数的情况下将数组保存到 mySQL 数据库中的单独行

node.js - NodeJs shell.openExternal 打开exe并最小化