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;
}
}
-
what do you mean with multidimensional?Nina Scholz– Nina Scholz2017年11月05日 18:35:05 +00:00Commented Nov 5, 2017 at 18:35
-
just a simple matrix.Michael– Michael2017年11月05日 18:37:19 +00:00Commented Nov 5, 2017 at 18:37
-
So actually twodimensional...trincot– trincot2017年11月05日 18:38:26 +00:00Commented Nov 5, 2017 at 18:38
-
indeed. eg. [[2, 1], [4, 3]]Michael– Michael2017年11月05日 18:39:08 +00:00Commented 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?trincot– trincot2017年11月05日 18:43:03 +00:00Commented Nov 5, 2017 at 18:43
1 Answer 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);
answered Nov 5, 2017 at 18:45
trincot
357k38 gold badges282 silver badges339 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-js