1

I'm trying to loop through an array of array, after each iteration, recursively call the function to loop through the arrays again, but one position further along the array of arrays. Code example below. Temp rows is just an example, the data could change and contain more or less arrays inside the outer array. Is there a way to do it without flattening the array?

tempRows = [[1,1,1], 
            [1,1,1], 
            [1,1,1]
            ]
num = 10;
func(start) {
  for (let i = 0; i < tempRows.length; i++) {
      for (let j = start; j < tempRows[i].length; j++) {
        console.log(start) // start is now one element forward
        //then loop through the rest of the elements as usual
       }
  }
 if ( start < num) {
  func(start + 1)
 } 
  return;
  
}
func(0)
maximosis
  • 89
  • 2
  • 8
  • 3
    Can you provide an example of your data? It will help to understand what you would like. so, specify the starting data, with your sub arrays and list the output that you would like to see. – This Guy Sep 15 '22 at 15:25
  • 1
    Where are you flattening the array? – Barmar Sep 15 '22 at 15:29
  • 1
    You need a check for the base case or you'll have infinite recursion. – Barmar Sep 15 '22 at 15:30
  • 1
    Sorry, up dated with sample data. So, when the function is called, it would then start at position 1 rather than 0 on the first array, and continue until the starting position is the last position. It will always be an array of arrays, but only as deep as nested as the example. – maximosis Sep 15 '22 at 15:37

2 Answers2

2

Adding a condition before each recursion will do the trick. In the following code, only the first two arrays (if they are) of each array will be recursed.

let tempRows = [[0, [1.1, 1.2, 1.3], [2.1, 2.2]], 
                [3, 4, 5], 
                [6, 7, 8]
               ]
           
let limit = 1;


function repeatWithException(multiArray) {

  multiArray.forEach((item, idx) => {
    
    if (!Array.isArray(item))
       console.log(item)
    else
     if (idx <= limit)
       repeatWithException(item);     
  
  })

}


repeatWithException(tempRows)
Charlie
  • 22,886
  • 11
  • 59
  • 90
0

Does this do what you want?

const data = [[1,2,3,4,5], ['a','b','c','d'], [true, false]]

const print = (input) => 
    (Array.isArray(input)) ? input.forEach(print) : console.log(input)
        
const go = ([first, ...rest]) => 
    first && (print([first, ...rest]), go(rest))

go(data)
Ben Aston
  • 53,718
  • 65
  • 205
  • 331