Splitting an array into chunks in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a function, let’s say chunk() that takes in an array arr of string / number literals as the first argument and a number n as second argument.

We are required to return an array of n subarrays, each of which contains at most −

arr.length / n elements.

The distribution of elements should be like this −

The first element goes in the first subarray, second in second, third in third and so on. Once we have one element in each subarray, we again start with filling the first subarray with its second element. Similarly, when all subarrays have two elements only after that we fill the third element in the first array and so on.

For example: If the input array is −

const input = [656, 756, 5345, 67, 43, 76, 54, 768, 34];

And the number n is 3,

Then the output should be −

const output = [
[ 656, 67, 54 ],
[ 756, 43, 768 ],
[ 5345, 76, 34 ]
];

Therefore, let’s write the code for this function −

We will Array.prototype.reduce() method over the original array to construct the desired array.

Example

The code for this will be −

const input = [656, 756, 5345, 67, 43, 76, 54, 768, 34];
const divideArray = (arr, size) => {
return arr.reduce((acc, val, ind) => {
const subIndex = ind % size;
if(!Array.isArray(acc[subIndex])){
acc[subIndex] = [val];
}else{
acc[subIndex].push(val);
};
return acc;
}, []);
};
console.log(divideArray(input, 3));

Output

The output in the console will be −

[ [ 656, 67, 54 ], [ 756, 43, 768 ], [ 5345, 76, 34 ] ]
Updated on 19-Oct-2020 10:58:00