2

I want to define a function that will create a nested array that is n-levels deep with n-elements in each level-1 array.

So, for example, the code below works for 2 levels:

 function genMatrix() {
    const matrix = [];
    let total = 0;
    for(let i=0; i<2; i++) {
      matrix[i] = [];
      for(let j=0; j<2; j++) {
        total++;
        matrix[i][j] = total;
      }
    }
    return matrix;
  }

This will output the following: [ [ 1, 2 ], [ 3, 4 ] ]

I know that I can extend this same idea by simply adding more nested loops. But I want a function that will generate a similar array of any level.

Something like this:

function genMatrix(levels) {... return matrix}

I was trying to do this recursively, but I didn't get very far :(

So how could I write a recursive function that creates an array of any depth in a similar way to the example above?

5
  • 1
    So n=3 would give [[[1,2,3],[4,5,6]]]? Commented Jan 2, 2018 at 19:16
  • 2
    the short answer is yes. the longer answer is, you need to define better what you're asking. Also, you're likely to get down votes if you simply ask us to do your homework and write it for you. Commented Jan 2, 2018 at 19:21
  • @elclanrs [ [ [1, 2, 3], [4,5, 6], [7, 8, 9] ], [ [10, 11, 12], [13, 14, 15], [16, 17, 18] ], [ [19, 20, 21], [22, 23, 24], [25, 26, 27] ] ] Commented Jan 2, 2018 at 19:22
  • tldr; 1) call the function recursively and use the result 2) each time the recursive function is called, pass in a correct (but different) value to ensure the base-case is reached (eg. level=1). - en.wikipedia.org/wiki/Recursion_(computer_science) Commented Jan 2, 2018 at 19:25
  • @elclanrs No, sorry if my question was unclear n=3 would give: [ [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ], [ [ 10, 11, 12 ], [ 13, 14, 15 ], [ 16, 17, 18 ] ], [ [ 19, 20, 21 ], [ 22, 23, 24 ], [ 25, 26, 27 ] ] ] Commented Jan 3, 2018 at 16:28

1 Answer 1

1

Here is the n-level nested array generator:

function getMatrix(n) {
  var total = 0, levels = n;
  function genMatrix(n) {
    var matrix = [];
    for (var i = 0; i < levels; i++) {
      matrix.push(n ? genMatrix(n - 1) : ++total);
    }
    return matrix;
  }
  return genMatrix(n)[0];
}

Test:

console.log(getMatrix(2));
// → [[1, 2], [3, 4]]

console.log(getMatrix(3));
// → [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [...], ...], ...]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is the type of output I was looking for. This clarifies things a lot.
You are welcome. It's really appreciated. Thank you too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.