Dividing an array – JavaScript

Let’s say, we are required to write a function 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. And 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 ]
];

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

Example

Following is the code −

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

This will produce the following output in console −

[ [ 656, 67, 54 ], [ 756, 43, 768 ], [ 5345, 76, 34 ] ]