/

How to Divide an Array into Multiple Equal Parts in JavaScript

How to Divide an Array into Multiple Equal Parts in JavaScript

Are you struggling with dividing an array into multiple equal parts in JavaScript? In this blog post, I will share with you two different solutions to tackle this problem.

Solution (A): Divide the Array into Equal Chunks

If you are uncertain about the number of groups you want to end up with, but you know you want a specific number of items in each new array you create, this solution is perfect for you.

Let’s take an array as an example:

1
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

To divide this array into chunks of 2 items, you can use the following code:

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

The result will be a new array of arrays:

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

You can also divide the array into chunks of 3 items by changing the value of n to 3.

Solution (B): Divide the Array into a Specific Number of Arrays

If you know the number of groups you want to create and are not concerned about the number of items in each new array, this solution is a great choice.

Using the same example array:

1
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

To divide the array into 2 arrays, you can use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
const n = 2;
const result = [[], []]; // Create an empty array of arrays

const wordsPerLine = Math.ceil(items.length / n);

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);
}
}

The result will be:

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

You can modify the value of n to divide the array into a different number of arrays.

Note that the original array is modified when using the splice() method in Solution (A).

I hope these solutions help you divide arrays into multiple equal parts in JavaScript! Feel free to try them out in your projects.

Tags: JavaScript, array manipulation, divide array, equal parts, coding tips