danday74
danday74

Reputation: 57056

Use JavaScript or Lodash to create multi dimensional array

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

Answers (4)

charlietfl
charlietfl

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

Akrion
Akrion

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

Conner
Conner

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

slider
slider

Reputation: 12990

With lodash you can use chunk:

const result = _.chunk(_.range(1, 21), 10);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Upvotes: 6

Related Questions