Here's a unique approach to handling arrays where you can dynamically change the lengths of the inner arrays without much hassle.
Although the code could be more concise, I've kept it verbose for better readability.
// Defining a function that takes in:
// an array
// length of the first array
// length of the second array
const arrayParser = (inArr,arr1len,arr2len) => {
// Creating a new array.
let outArr = [];
// Using forEach loop to iterate over input array with index.
inArr.forEach((val,idx) => {
// Checking if the current index should start a new sub-array based on modulo operations.
if (idx%(arr1len+arr2len)===0 || idx%(arr1len+arr2len)===arr1len) {
// Adding a new empty array when needed.
outArr.push([]);
}
// Appending value to the last sub-array in the output multidimensional array.
outArr[outArr.length-1].push(val);
});
// Returning the resulting array.
return outArr;
};
// Sample Single Dimensional Array
const singleArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
// Testing different configurations
console.log(arrayParser(singleArray,10,4));
console.log(arrayParser(singleArray,2,4));
console.log(arrayParser(singleArray,3,4));
console.log(arrayParser(singleArray,4,3));
console.log(arrayParser(singleArray,1,2));
This method doesn't require calculating indexes as long as you know the lengths of the interior arrays beforehand.
Here's how a 4,3 setup plays out:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
New arrays at indices 0 and 4.
4+3
index total Modulus
0 % 7 = 0 <-- push [], push 1
1 % 7 = 1 <-- push 2
2 % 7 = 2 <-- push 3
3 % 7 = 3 <-- push 4
4 % 7 = 4 <-- push [], push 5
5 % 7 = 5 <-- push 6
6 % 7 = 6 <-- push 7
7 % 7 = 0 <-- push [], push 8
8 % 7 = 1 <-- push 9
9 % 7 = 2 <-- push 10
10 % 7 = 3 <-- push 11
11 % 7 = 4 <-- push [], push 12
12 % 7 = 5 <-- push 13
13 % 7 = 6 <-- push 14
Result:
[[1,2,3,4],[5,6,7],[8,9,10,11],[12,13,14]]