1

Here is a generator creating a normal array. What is the quickest way of creating a multi dimensional array?

let seq = [...makeSequence(100)];

* makeSequence(max) {
   for (let i = 0; i < max; i++) {
     yield i;
   }
}
5
  • what do you mean with multidimensional? Commented Nov 5, 2017 at 18:35
  • just a simple matrix. Commented Nov 5, 2017 at 18:37
  • So actually twodimensional... Commented Nov 5, 2017 at 18:38
  • indeed. eg. [[2, 1], [4, 3]] Commented Nov 5, 2017 at 18:39
  • And what do you expect to be iterated? The outer array? What would an individual yield return? An array? Commented Nov 5, 2017 at 18:43

1 Answer 1

1

If the iterator should return the top-level elements (which would be arrays themselves), then you could use recursion and so support any depth of array nesting:

function * makeSequence(max, dimensionCount = 1) {
   for (let i = 0; i < max; i++) {
     yield dimensionCount <= 1 ? i : [...makeSequence(max, dimensionCount-1)];
   }
}

let seq = [...makeSequence(5, 2)];

console.log(seq);

Sign up to request clarification or add additional context in comments.

Comments

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.