Reputation: 57056
I want to create a multi-dimensional array like this using Lodash or vanilla JS:
[
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
etc
]
This is a simplistic example since I want this pattern to continue up to 1,000,000 but for demonstration 1 to 20 is fine.
Any ideas? I've tried _.range(20)
so far but I need this Array to be multi-dimensional. Thanks
Upvotes: 2
Views: 2810
Reputation: 171669
Using nested native Array#from()
const
limit = 100,
fr = Array.from;
const res = fr({ length:limit/10 }, (_,i) => fr({ length:10 }, (_,j) => i*10 + j+1 ));
console.log(res)
Upvotes: 5
Reputation: 18525
Looking at the ES6 Array.from
documentation you can see a range generator function:
const range = (start, stop, step) => Array.from({ length: (stop - start) / step }, (_, i) => start + (i * step));
So with that in mind you could generate the range via:
range(1, 21, 1) // account for the 0 with the 21 otherwise you get 1-19
Then all that is missing is the chunk
function:
const range = (start, stop, step) => Array.from({ length: (stop - start) / step }, (_, i) => start + (i * step));
const chunkBy = (arr, by=2) => arr.reduce((r,c,i) => (i%by==0 ? r.push([c]) : r[r.length-1] = [...r[r.length-1], c], r), [])
console.log(chunkBy(range(1,21,1), 10))
The chunkBy
uses Array.reduce
& the %
operator to chunk
the data.
Upvotes: 3
Reputation: 31060
With vanilla javascript:
x = []
for (i=1; i<=20; i=i+10) {
y = []
for (j=0; j<10; j++) {
y.push(i + j)
}
x.push(y)
}
console.log(x)
For anyone who's interested, I time clocked these answers and this is the fastest. Using 1 million entries, this clocks at .100 seconds. Lodash chunk clocks close behind at .110s. Array.from
lags behind at .254s.
Upvotes: 3