1

Imagine I have an Item that has an array of Items and any of the Items in the Array has an array of Items and so on. So i have an infinite level of Items and i want to know how to get to all of them in node.js. Like this:

    Item1
     /     \
   Item2    Item3
            /    \
          Item4   Item5

Item1 is an array. Item2 and Item3 another array and so on.

tech_boy
  • 195
  • 3
  • 13
shiqo
  • 103
  • 3
  • 12

1 Answers1

0

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

Recursively flatten each element in the array if it's an array, otherwise append it.

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

Hope this helps. Cheers!

jonathangersam
  • 1,137
  • 7
  • 14