How to divide an array into multiple equal parts in JS

I have a question.

The array contains many items and I want to divide it into multiple blocks.

I came up with 2 completely different solutions.

A) The first one is to divide the array into equal blocks, such as blocks of 2 or 3 items. B) The second is to create n blocks and add an equal set of variables to it

We split in different ways and reasons. Solution (A) is very useful when you don’t know how many groups there will be in the end and it doesn’t matter, but you know there are X items in each new array created

Solution (B) is good when you know how many groups to create and are strict about it, but you don't have to care about how many items each new array will contain.

In other words, an array like this

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using solution (A), we can create a chunk of 2 projects and get

[ 1, 2 ]
[ 3, 4 ]
[ 5, 6 ]
[ 7, 8 ]
[ 9, 10 ]

or chunks of 3 items:

[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]
[ 10 ]

With solution (B) we can divide the array in 2 arrays, and get:

[ 1, 2, 3, 4, 5 ]
[ 6, 7, 8, 9, 10 ]

Or we can divide the array in 3 arrays, and get:

[ 1, 2, 3, 4 ]
[ 4, 5, 6, 7]
[ 8, 9, 10 ]

Here is the implementation of (A):

const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] //… your array, filled with values
const n = 3 //tweak this to add more items per line

const result = new Array(Math.ceil(items.length / n))
  .fill()
  .map(_ => items.splice(0, n))

In this example result is a new array of arrays:

[ 
  [ 1, 2, 3 ], 
  [ 4, 5, 6 ], 
  [ 7, 8, 9 ], 
  [ 10 ] 
]

Here is the implementation of (B), assuming you want an array of 3 arrays as a result:

const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] //… your array, filled with values

const n = 3
const result = [[], [], []] //we create it, then we'll fill it

const wordsPerLine = Math.ceil(items.length / 3)

for (let line = 0; line < n; line++) { for (let i = 0; i < wordsPerLine; i++) { const value = items[i + line * wordsPerLine] if (!value) continue //avoid adding “undefined” values result[line].push(value) } }

In this example result is

[ 
  [ 1, 2, 3, 4 ], 
  [ 5, 6, 7, 8 ], 
  [ 9, 10 ] 
]  

More js tutorials: