Search code examples
javascriptarraysfunctionsublist

cycling through each individual sublist


Write a function that takes a list of list of numbers and prints out elements by cycling through each individual sublist.Basically, given an input like:

       [
          [1, 2, 3],
          [10, 20, 30],
       ]

Print out the first elements of each sublist, followed by the second elements, etc. The expected output is: 1 10 2 20 3 30


Solution

  • Simple for loop?

    var arr = [[1, 2, 3], [10, 20, 30]];
    
    
    for (var i = 0; i < arr[0].length; i++) {
      for (var j = 0; j < arr.length; j++) {
        document.write(arr[j][i] + ' ');
      }
    }