Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
If the final chunk of a chunked array can't be split evenly then add empty strings into the final chunk

I have this problem where I want to split an array of elements into equal chunks of three. But if the final chunk can't be split evenly then add empty strings.

I am using lodash _.chunk method but not sure how to add extra empty strings in the final chunk.

// 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 [[{}, {}, {}], [{}, '', '']].

Can somebody please let me know how to achieve this in JS?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First, you will need to increase the array length until it get a divisible length by 3 after that you could slice the array simply using slice method like this

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));

about 4 years ago · Juan Pablo Isaza Relatório

0

I'm not sure why everyone is rewriting chunk. Do the chunking with lodash's _.chunk like you are, then just fill in the last chunk.

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%; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda