How to divide an array in multiple equal parts in JS
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 ]
]
Note that the original array is modified by using
splice()
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 ]
]
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025