Just for Looping Through Multidimensional Array to iterate each item in javascript

this problem how can i solve with for loop not use a built-in function

let array = [

    [1,2,3],

    [4,5,6],

    [7,8,9],

    [[10,11,12],13,14],

    [[15,16,16],[17,18,[19,20]]]

]

Something like this using recursion.

function flatForEach(arg, f) {
  if (!Array.isArray(arg)) {
    return f(arg);
  }
  for (const element of arg) {
    flatForEach(element, f);
  }
}

flatForEach(array, console.log);
1 Like

i need to just for loop way not any recursive or built-in function
is it possible

No it’s not possible without recursion unless you can guarantee how many dimensions there are.

Here’s one that works for four dimensions or less. It’s ugly and I don’t support anyone using it.

function fourDimensionalForEach(array, f) {
  for (const first of array) {
    if (Array.isArray(first)) {
      for (const second of first) {
        if (Array.isArray(second)) {
          for (const third of second) {
            if (Array.isArray(third)) {
              for (const fourth of third) {
                f(fourth);
              }
            } else {
              f(third);
            }
          }
        } else {
          f(second);
        }
      }
    } else {
      f(first);
    }
  }
}

fourDimensionalForEach(array, console.log);

thank for details explain to me