I came across this problem recently which demanded to split an array into equal chunks in javascript and the array size is in the multiple of the chunk size. Of course, I found many solutions on the internet but I wanted a solution that doesn’t include inbuild functions of javascript, and I didn’t find anything similar to that. In the end, I tried to solve this myself and this is my solution. Hope it helps those people who are interested in this approach.
ES5 approach –
/*
* @param arr - Array of elements
* @param chunkSize - The size of child array
*
* The only restriction in this problem is that the array size should be in the multiple of chunk size,
* so that it can be splitted equally.
*/
function splitArrayIntoEqualChunks(arr, chunkSize){
/*
firstIdx - To maintain the first Index of child arrays.
chunkedArr - The result array which would contain the splitted arrays
*/
let firstIdx = 0, chunkedArr = [];
for (let i = 0; i < arr.length; i++) {
if ((i + 1) % chunkSize === 0) {
let innerArr = []; //This array would contain a single chunk of splitted array
for (let j = firstIdx; j <= i; j++) {
innerArr.push(arr[j]);
firstIdx = i + 1;
}
chunkedArr.push(innerArr);
}
}
return chunkedArr;
}
ES6+ approach –
const splitArrayIntoEqualChunks = (arr, chunkSize) => {
let firstIdx = 0, chunkedArr = [];
for (let i = 0; i < arr.length; i++) {
if ((i + 1) % chunkSize == 0) {
let innerArr = []; //This array would contain a single chunk of splitted array
for (let j = firstIdx; j <= i; j++) {
innerArr.push(arr[j]);
firstIdx = i + 1;
}
chunkedArr.push(innerArr);
}
}
return chunkedArr;
}
When we pass the expected arguments and make a call to the above function, like this –
let arr = [1,2,3,4,5,6,7,8,9,10,11,12], chunkSize = 4;
console.log(splitArrayIntoEqualChunks(arr, chunkSize));
arr = [1,2,3,4,5,6,7,8,9,10,11,12]; chunkSize = 2;
console.log(splitArrayIntoEqualChunks(arr, chunkSize));
arr = [1,2,3,4,5,6,7,8,9,10,11,12]; chunkSize = 3;
console.log(splitArrayIntoEqualChunks(arr, chunkSize));
The output will be printed something like this respectively –
- [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] //ChunkSize = 4
- [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]] //ChunkSize = 2
- [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] //ChunkSize = 3
Here is the working JsFiddle link to the solution.
So, that was the solution to split an array into equal chunks in javascript without using any specific inbuilt functions. Hope this helps 🙂
Also read –
How to get the date range between the two dates using moment.js?
Top 15 Nodejs Interview Questions – 2022