Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!