I had a problem.

An array contained a lot of items, and I wanted to divide it into multiple chunks.

I came up with 2 completely different solutions.

A) The first was to divide the array in equal chunks, for example chunks of 2 or 3 items B) The second was to create n chunks and add an equal variable set of items to it

It’s different how and why we divide. Solution (A) is great when you don’t know how many groups you’re going to end up with, and don’t care, but you know you want X items in each new array you create

Solution (B) is great when you know how many groups you want to create, and you are strict about that, but don’t care how many items each new array will contain.

In other words, with an array like

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

With solution (A) we can create chunks of 2 items, 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 ]
]
```

Download my free JavaScript Beginner's Handbook and check out my JavaScript Course!

#### More js tutorials:

- How I fixed a "cb.apply is not a function" error while using Gitbook
- JavaScript Expressions
- The Object getOwnPropertyDescriptor() method
- The String repeat() method
- How to get the unique properties of a set of objects in a JavaScript array
- Destructuring Objects and Arrays in JavaScript
- The Object freeze() method
- JavaScript labeled statements
- How to get the first n items in an array in JS