I have the following problem, I need to split an array into at least n even chunks, but the first element of every array except the first is the last element of the previous array. The last array can have a smaller number of elements if there aren't enough elements.
Edge case discovered by ~ @trincot
If it is not possible to split into n requested chunks, split to the closest number of chunks that when is possible.
Input:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Expected output n=3:
[[1, 2, 3, 4, 5], [5, 6, 8, 9, 10], [10, 11]]
I need a solution in JavaScript but feel free to submit other languages, I will translate it and submit the solution in JavaScript.
My not working attempt, I couldn't figure out how to start with desired chunk number so I used chunk size here with intention to figure out chunk size from chunk number later.
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const range = 4;
const res = [array.slice(0, range)];
let start = range;
let end = range * 2;
while (true) {
console.log(start, end);
res.push(array.slice(start, end));
start += range;
end += range;
if (start >= array.length) {
break;
}
}
console.log(res);