Skip to content

How to divide an array in multiple equal parts in JS

New Course Coming Soon:

Get Really Good at Git

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 ] 
]
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: