Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Example Input and Output
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 ]
];
How It Works
We will use the Array.prototype.reduce() method over the original array to construct the desired array. The key insight is using the modulo operator (%) to cycle through the subarrays.
Implementation
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));
[ [ 656, 67, 54 ], [ 756, 43, 768 ], [ 5345, 76, 34 ] ]
Alternative Approach Using forEach
Here's another way to achieve the same result using forEach:
const divideArrayAlt = (arr, size) => {
const result = Array(size).fill().map(() => []);
arr.forEach((element, index) => {
const subIndex = index % size;
result[subIndex].push(element);
});
return result;
};
const input2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(divideArrayAlt(input2, 4));
[ [ 1, 5, 9 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]
Key Points
- The modulo operator (%) is used to cycle through subarrays:
index % size - Elements are distributed in round-robin fashion across subarrays
- The
reducemethod builds the result array incrementally - Each subarray is initialized as an empty array when first accessed
Conclusion
Dividing arrays into equal parts using round-robin distribution is efficiently handled with the modulo operator. The reduce method provides a clean functional approach to build the divided array structure.
