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
Split one-dimensional array into two-dimensional array JavaScript
We are required to write a function that takes in a one-dimensional array as the first argument and a number n as the second argument and we have to make n subarrays inside of the parent array (if possible) and divide elements into them accordingly.
If the array contains 9 elements and we asked to make 4 subarrays, then dividing 2 elements in each subarray creates 5 subarrays and 3 in each creates 3, so in such cases we have to fallback to nearest lowest level (3 in this case) because our requirement is to distribute equal number of elements in each subarray except the last one in some special cases.
Problem Example
// if the input array is: const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; // and the number is 2 //then the output should be: const output = [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ];
How It Works
The algorithm calculates items per row using Math.ceil(arr.length / rows). For each element, it determines which row it belongs to using Math.floor(index / itemsPerRow), then builds the result using reduce().
Example
const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
const splitArray = (arr, rows) => {
const itemsPerRow = Math.ceil(arr.length / rows);
return arr.reduce((acc, val, ind) => {
const currentRow = Math.floor(ind / itemsPerRow);
if(!acc[currentRow]){
acc[currentRow] = [val];
}else{
acc[currentRow].push(val);
};
return acc;
}, []);
};
console.log(splitArray(arr, 2));
console.log(splitArray(arr, 3));
console.log(splitArray(arr, 4));
Output
[ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ] [ [ 'A', 'B', 'C' ], [ 'D', 'E', 'F' ], [ 'G', 'H', 'I' ] ] [ [ 'A', 'B', 'C' ], [ 'D', 'E', 'F' ], [ 'G', 'H', 'I' ] ]
Alternative Method Using slice()
const splitArraySlice = (arr, rows) => {
const itemsPerRow = Math.ceil(arr.length / rows);
const result = [];
for (let i = 0; i < arr.length; i += itemsPerRow) {
result.push(arr.slice(i, i + itemsPerRow));
}
return result;
};
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(splitArraySlice(numbers, 3));
[ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]
Comparison
| Method | Complexity | Readability | Performance |
|---|---|---|---|
reduce() |
Medium | Functional style | Good |
slice() |
Simple | Very clear | Better |
Conclusion
Both methods effectively split arrays into equal chunks. The slice() approach is simpler and more readable, while reduce() offers a functional programming style.
