Tengo este problema en el que quiero dividir una matriz de elementos en partes iguales de tres. Pero si el fragmento final no se puede dividir de manera uniforme, agregue cadenas vacías.
Estoy usando el método lodash _.chunk pero no estoy seguro de cómo agregar cadenas vacías adicionales en el fragmento final.
// I will get unknown number elements in the array. const arr1 = [{elem1}, {elem2}, {elem3}, {elem4}] // above array does have 4 elements. If I use _.chunk I will get something like [[{elem1},{elem2},{elem3}], [{elem4}]] // I am looking to get something like [[{}, {}, {}], [{}, '', '']].¿Puede alguien decirme cómo lograr esto en JS?
Primero, deberá aumentar la longitud de la array hasta que obtenga una longitud divisible por 3 , después de eso, podría dividir la matriz simplemente usando el método de slice como este
let arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'bar'}, {foo: 'bar'}]; function split(arr){ let res = []; while(arr.length % 3 != 0){ arr.push({foo: 'bar'}); } for(let i = 0; i < 3; i++) res.push(arr.slice(i * 2, i * 2 + (arr.length / 3))) return res; } console.log(split(arr));No estoy seguro de por qué todos están reescribiendo chunk . Haga la fragmentación con _.chunk de _.chunk como lo está haciendo, luego solo complete la última fracción.
let chunkedArray = [ [{foo:'bar'},{foo:'bar'},{foo:'bar'}], [{foo:'bar'},{foo:'bar'},{foo:'bar'}], [{foo:'bar'}], ]; const chunkSize = 3; const filler = ''; // fill in // Create a new array, chunkedArray = [ // with all of the chunks except the last one ...chunkedArray.slice(0,-1), // Add the last chunk [ // with all of its contents ...chunkedArray[chunkedArray.length - 1], // plus the contents of a new array, the length of a chunk minus the length // of the last chunk, filled with an empty string (or whatever) ...new Array(chunkSize - chunkedArray[chunkedArray.length - 1].length).fill(filler) ] ]; // now chunkedArray is complete, all arrays the same size console.log(chunkedArray); .as-console-wrapper { max-height: 100% !important; top: 0; } .as-console { height: 100%; }