Home > front end >  Move starting position for a nested loop after each recursive call
Move starting position for a nested loop after each recursive call

Time:09-16

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)

CodePudding user response:

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)

CodePudding user response:

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)

  • Related