Tengo una matriz como:
var myArray = [[1, 2, 3, 4], [5, 6], [7, 8, 9], [10]];Cómo puedo reordenar esta matriz con las siguientes reglas:
myArray[0][0] para reducir el tamaño a 2 elementos (los valores 1,2 permanecen, 3,4 va a la siguiente matriz)Lo que ya intento es:
function conditionalChunk(array, size, rules = {}) { let copy = [...array], output = [], i = 0; while (copy.length) output.push( copy.splice(0, rules[i++] ?? size) ) return output } conditionalChunk(myArray, 3, {0:2});pero en ese caso, necesito poner reglas para todas las matrices en la matriz, necesito conocer una cantidad de elementos para todas las matrices en la matriz, y eso es lo que quiero evitar.
¿Hay alguna forma elegante de hacerlo?
Array#flat , por lo que tenía que realizar un seguimiento de los índices y la longitud de cada elemento.
let i = 0; let itemLength = array[0]?.length; Después de aplanar la matriz, uso Array#reduce para recorrer los elementos y establecer el valor initialValue en una matriz vacía.
Obtengo el último elemento de la matriz y compruebo si su longitud ha alcanzado el máximo permitido (que debería ser el establecido en el argumento de rules para ese índice o el argumento de size ).
Si no se ha alcanzado el máximo, empujo el elemento actual a la última matriz. Si es así, creo una nueva matriz, con el elemento como el único elemento
array.flat().reduce((acc, cur) => { if (acc.length === 0) acc.push([]); // Just for the first iteration if (acc.at(-1).length < (rules[i] ?? size)) acc[acc.length - 1].push(cur); else acc.push([cur]); Si luego disminuye el valor de itemLength o lo establece en la longitud de la siguiente matriz. e incrementar la variable i al siguiente índice
itemLength = itemLength === 0 ? (array[++i] ?? []).length : --itemLength; let array = [[1, 2, 3, 4], [5, 6], [7, 8, 9], [10]]; function conditionalChunk(array, size, rules = {}) { let i = 0; let itemLength = array[0]?.length; return array.flat().reduce((acc, cur) => { if (acc.length === 0) acc.push([]); // Just for the first iteration if (acc.at(-1).length < (rules[i] ?? size)) acc[acc.length - 1].push(cur); else acc.push([cur]) itemLength = itemLength === 0 ? (array[++i] ?? []).length : --itemLength; return acc; }, []); } console.log(JSON.stringify(conditionalChunk(array, 3, { 0: 2 })));Esto es lo que se me ocurrió. Pegue el código en la consola de Chrome y pruébelo.
var myArray = [[1, 2, 3, 4], [5, 6], [7, 8, 9], [10]]; //Getting initial lengths of inner arrays [4, 2, 3, 1] var lengths = []; myArray.forEach((arr) => {lengths.push(arr.length);}); // Extracting the elements of all the inner arrays into one array. var allElements = [].concat.apply([], myArray); // Updating the lengths of first and last inner arrays based on your requirement. var firstArrLen = 2; var lastArrLen = lengths[lengths.length -1] + (lengths[0] - 2) lengths[0] = firstArrLen; lengths[lengths.length -1] = lastArrLen; // Initializing the final/result array. var finalArr = []; // Adding/Pushing the new inner arrays into the finalArr for(var len of lengths) { var tempArr = []; for(var i=0; i<len; i++) { tempArr.push(allElements[i]); } finalArr.push(tempArr); for(var i=0; i<len; i++) { // removes the first element from the array. allElements.shift(); } } console.log(finalArr);Los requisitos no estaban tan claros y no sé por qué harías nada de eso, pero aquí tienes tu solución: he escrito una función que puedes usar para limitar la cardinalidad de los subArreglos.
var myArray = [[1, 2, 3, 4], [5, 6], [7, 8, 9], [10]]; function reorderArray(arr) { let buff = []; let newArr = []; let maxSubarrCardinality = 2; //flatMapping second level elements //in a single level buffer for (subArr of arr) { for (elem of subArr) { buff.push(elem); } } //Inserting elements one at the time //into a new array for (elem in buff) { //when the new array is empty //push in the new array the first empty subArray if (newArr.at(-1) == undefined) newArr.push([]); //if the last subArray has reached //the maxCardinality push a new subArray else if (newArr.at(-1).length >= maxSubarrCardinality) { newArr.push([]); newArr.at(-1).push(elem); } //if none of the previous special cases //just add the element to the last subArray of the newArray else { newArr.at(-1).push(elem); } } return newArr; } myArray = reorderArray(myArray);