Here's how to do it, I am expanding a bit to allow you to arbitrarily pass array lengths, this allows PM to change its mind at any time, and it doesn't really matter.
This can be cleaned a bit, I would like to leave it more detailed so that it is easier to read.
// Setup the function getting in: // an array // first array length // second array length const arrayParser = (inArr,arr1len,arr2len) => { // Create a new array. let outArr = []; // Basic forEach is basic, we need the value and the index. inArr.forEach((val,idx) => { // If the index modulus of the total of the two array lengths is: // 0 OR the first array length // Push a new empty array. if (idx%(arr1len+arr2len)===0 || idx%(arr1len+arr2len)===arr1len) { // Create a new array with the current value outArr.push([]); } // Push the value to the last array in the out multidimensional array outArr[outArr.length-1].push(val); }); // You got it.. return the array. return outArr; }; // 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]; // Parse it. // Expects: // A Single Dimensional Array // Length of the first array // Length of the second array 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 works because you know the length of each of the internal arrays, so you do not need to figure anything out.
4.3 sets came out here.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] Push a new array at 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 Returns [[1,2,3,4],[5,6,7],[8,9,10,11],[12,13,14]]