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?
CodePudding user response:
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));
CodePudding user response:
Use Array.prototype.concat()
to adjust array size to multiple of 3 and Array.prototype.reduceRight()
to split into chunks:
const src = [{el: '1'}, {el: '2'}, {el: '3'}, {el: '4'}, {el: '5'}, {el: '6'}, {el: '7'}]
const chunkOfThree = arr =>
arr
.concat(
arr.length%3
? Array(3-arr.length%3).fill('')
: []
)
.reduceRight((r,_,__,s) =>
(r.push(s.splice(0,3)),r),[])
console.log(chunkOfThree(src))
.as-console-wrapper{min-height:100%}
CodePudding user response:
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%; }