Search code examples
javascriptlodash

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


Solution

  • 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.