The array.slice() method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    // do whatever
}

The last chunk may be smaller than chunkSize. For example when given an array of 12 elements the first chunk will have 10 elements, the second chunk only has 2.

Note that a chunkSize of 0 will cause an infinite loop.

Answer from Blazemonger on Stack Overflow
🌐
Futurestud.io
futurestud.io › tutorials › split-an-array-into-smaller-array-chunks-in-javascript-and-node-js
Split an Array Into Smaller Array Chunks in JavaScript and Node.js
February 25, 2021 - This package comes with the .chunk(<size>) method splitting the given array into arrays of the given size. Wrapping an array using the @supercharge/collections package creates a collection instance. You must end the chain with .all() to retrieve the underlying JavaScript array:
🌐
Medium
vicentebryam.medium.com › splitting-array-into-chunks-34dc9524afd4
Splitting Array Into Chunks
April 19, 2021 - Note that I’ll be using JavaScript to solve this problem! ... The problem tells us that we need to create a function where it holds an array and chunk size (integer) as arguments. The goal of this function is to divide arrays into subarrays depending on the chunk size.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › slice
Array.prototype.slice() - JavaScript | MDN
The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › split-an-array-into-chunks-in-javascript
Split an Array into Chunks in JavaScript - GeeksforGeeks
July 11, 2025 - The array reduce() method is used to iterate over the array and perform some operations to split the array into chunks.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › split
String.prototype.split() - JavaScript | MDN
The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
🌐
Codewars
codewars.com › kata › 633ffeb1b8d020005747a976
Split array into chunks | Codewars
October 7, 2022 - Task In this Kata, you will be given an array arr of integers and a number n >= 0. Write a function that splits passed array into smaller chunks with size n. Notes Given arr may be empty...
Find elsewhere
🌐
DEV Community
dev.to › readwanmd › chunking-an-array-in-javascript-four-ways-compared-48ok
Chunking an Array in JavaScript: Four Ways Compared - DEV Community
July 6, 2024 - Explanation: This function iterates through the array in steps of the specified chunk size. It slices the array at each step and adds the resulting sub-array to the result array (res).
🌐
DEV Community
dev.to › domhabersack › how-to-split-arrays-into-equal-sized-chunks-198h
How to split arrays into equal-sized chunks - DEV Community
January 6, 2021 - To split six ducks into groups of four, we would need 1.5 chunks, because 6 divided by 4 is 1.5. Each chunk is an array. Because there are no half arrays, we round the result to the next-largest integer with Math.ceil(). For our six ducks, we need to use two chunks to split them in groups of four.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › split array into chunks
Split a JavaScript array into chunks - 30 seconds of code
November 7, 2023 - Using that number, you can create a new array with the specified length, using Array.from(). The second argument of Array.from() is a mapping function that will be called for each element of the new array. Using that in combination with Array.prototype.slice(), you can map each element of the new array to a chunk the length of size. If the original array can't be split evenly, the final chunk will contain the remaining elements.
🌐
W3Schools
w3schools.com › jsref › jsref_split.asp
JavaScript String split() Method
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › bifurcate array
How can I split a JavaScript array into two groups? - 30 seconds of code
October 9, 2023 - Array.prototype.reduce() is used with a callback function that will determine which group each element belongs to. A truthy value will place the element in the first group, while a falsy value will place it in the second group.
🌐
Programiz
programiz.com › javascript › examples › split-array
JavaScript Program to Split Array into Smaller Chunks
// program to split array into smaller chunks function splitIntoChunk(arr, chunk) { while(arr.length > 0) { let tempArray; tempArray = arr.splice(0, chunk); console.log(tempArray); } } const array = [1, 2, 3, 4, 5, 6, 7, 8]; const chunk = 2; splitIntoChunk(array, chunk);
🌐
Our Code World
ourcodeworld.com › articles › read › 278 › how-to-split-an-array-into-chunks-of-the-same-size-easily-in-javascript
How to split an array into chunks of the same size easily in Javascript | Our Code World
October 12, 2016 - The map function calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. The function will return an array with a length defined by the division of the length of the providen ...
🌐
MSR
rajamsr.com › home › javascript split array into chunks with best 7 examples
JavaScript Split Array into Chunks With Best 7 Examples | MSR - Web Dev Simplified
March 3, 2024 - This JavaScript function, named chunkArray(), takes an array and a chunk size as input. It divides the input array into smaller arrays of the specified chunk size and returns them as a new array called chunkedArray.
Top answer
1 of 3
6

First: Since you already know how many chunks you want, there's no point in checking if the chunk exists and otherwise declare it. In general terms, you should not need to check for objects you can define deterministically.

So instead of doing this check on each loop:

if (typeof result[i] == 'undefined'){
  result[i] = [];
}

create an array of N empty arrays beforehand.

const result = Array.from(Array(chunks),item=>[]);

Second: Albeit the performance difference is negligible, checking for i's value and conditionally reassigning it is less efficient than using the modulo operator on its value regardless

So instead of

results[i].push(...)
i++
i = (i == chunks) ? 0 : i;

You can do

results[i % chunks].push(...)
i++

With the above, your function could be expressed as

function usingShift(myArray, chunks=5){
  const copiedArray = myArray.slice(),
        result=Array.from(Array(chunks),item=>[]);
  let i=0;
  while(copiedArray.length){
    result[i % chunks].push(copiedArray.shift());
    i++;
  }
  return result;
}

Third: As you've been told, shifting from an array is expensive. I understand you're doing it because you want to populate the chunks in the same order of the original array. However you can achieve the same popping from the a reversed array:

If you declare

const a = myArray.slice().reverse();

You can replace the usage of shift with

result[i].push(a.pop());

The function would be something like:

function usingPop(myArray, chunks=5){
  const reversedArr = myArray.slice().reverse(),
        result=Array.from(Array(chunks),item=>[]);
  let i=0;
  while(reversedArr.length){
    result[i % chunks].push(reversedArr.pop());
    i++;
  }
  return result;
}

However... you'd still be copying the array and performing a mutation on the copy. @Miklós Mátyás solution has the advantage of populating the result without copying nor extracting items from the source array. Now, you haven't said the source array will be always the same (9 elements from 1 to 9). It could as well have repeated/unsorted items, so his solution should take into account not the item itself but its index, which can be expressed as:

function filterByModulo(myArray, chunks=5){
  return Array.from(Array(chunks),(_,modulo)=>{
    return myArray.filter((item,index) =>  index % chunks === modulo);
  });
}

That's pretty clean, but it's filtering on the original array as many times as chunks you want, so it's performance degrades according to the source array length AND the chunk quantity.

Personally I believe this is a case in which reduce would be more appropiate and pretty concise, while avoiding the copying or mutation of the source array.

function usingReduce(myArray,chunks=5) {
   const result=Array.from(Array(chunks),i=>[]);

   return myArray.reduce( (accum,item,index)=>{ 
      accum[index%chunks].push(item);
      return accum;
   }, result);
}

Finally there's the classic for loop

function classicFor(sourceArr, chunks=5) {
  const lengthOfArray=sourceArr.length;
  const result=Array.from(Array(chunks),i=>[]);
   
  for(let index=0; index<lengthOfArray ; index++) {
     result[index % chunks ].push(sourceArr[index]);
  }
  return result;
}

I made a test case at JSPerf in which it shows that the for loop is the most efficient. (I threw in forEach and for..of implementations too).

Running with a source array of 5000 items and 5 chunks shows that using pop on the source is more efficient than using shift by a 2.89x factor. It even looks more efficient that reduce. The classic for loop is the fastest whereas filtering N times comes up last by a ratio of 9x the modulo filtering.

If you use a source of 100000 items and 15 chunks the classic for is still the most efficient (still 9x modulo filtering) but the other implementations do scale a bit better than modulo filtering.

2 of 3
2

If you want to make the code "as efficient as possible" then avoid additional function calls - that includes iterator methods like Array.map(), Array.forEach(), etc., and while it would allow the code to be written in a more readable way, the ES6 for...of loop would also affect efficiency because it calls an iterator function for each element in the array.

I suggest using a basic for loop after creating an array of arrays (for each chunk). As others have mentioned, modulo division can be used to determine which sub-array to put each element into.

function into_subarrays(myArray, chunks=2){
  const result = Array(chunks);
  for (let i = chunks; i--; ) {
    result[i] = [];  //initialize sub-arrays
  }
          
  for(let i = 0, length = myArray.length; i < length; i++) {
    result[i%chunks].push(myArray[i]);
  }
  return result;
}
const a = [1,2,3,4,5,6,7,8,9];
console.log(into_subarrays(a, 2));

Notice the first loop to set the arrays of result iterates from chunks down to zero - this minimizes the number of operations in the for loop conditions. This wouldn't work for the second loop because the order of i values is important.

I see the function has a default parameter value for chunks - this is an ES6 feature. While not specifically ES6 features, the let and const keywords can be used to declare variables scoped to the blocks they are contained in.

In the existing code there are these lines towards the end of the while block:

result[i].push(a.shift());
i++;
i = (i == chunks) ? 0 : i; //Wrap around chunk selector

Whenever I see a pre/post increment operator on a single line I look to see if it could be combined with another operation - e.g.

  result[i++].push(a.shift());

or

i = (++i == chunks) ? 0 : i; //Wrap around chunk 

Also, prefer using === over == to avoid unnecessary type coercion.

🌐
Domhabersack
domhabersack.com › blog › how to split arrays into equal-sized chunks
How to split arrays into equal-sized chunks — Dom Habersack
January 7, 2020 - To split six ducks into groups of four, we would need 1.5 chunks, because 6 divided by 4 is 1.5. Each chunk is an array. Because there are no half arrays, we round the result to the next-largest integer with Math.ceil(). For our six ducks, we need to use two chunks to split them in groups of four.
🌐
Stack Abuse
stackabuse.com › how-to-split-an-array-into-even-chunks-in-javascript
How to Split an Array into Even Chunks in JavaScript
August 25, 2021 - In this tutorial, we'll take a look at how to split an array or list into even chunks of N size in JavaScript, using slice() and splice(), with examples.
🌐
JavaScript in Plain English
javascript.plainenglish.io › day-52-can-you-chunk-an-array-into-smaller-pieces-d1e58e6ecfc6
Day 52: Can You Chunk an Array Into Smaller Pieces? | by Dipak Ahirav | JavaScript in Plain English
July 7, 2025 - function chunkArray(array, size) { const result = []; for (let i = 0; i < array.length; i += size) { result.push(array.slice(i, i + size)); } return result; } // Example: const arr = [1, 2, 3, 4, 5, 6, 7]; console.log(chunkArray(arr, 3)); // [[1,2,3],[4,5,6],[7]] Pagination: Break data into ...
🌐
QuickRef.ME
quickref.me › home › how to split an array into chunks in javascript - quickref.me
How to split an array into chunks in JavaScript - QuickRef.ME
In this Article we will go through how to split an array into chunks only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.