I need to chunk an array of objects so i write:
JavaScript
x
12
12
1
function conditionalChunk(array, size, rules = {}) {
2
let copy = [array],
3
output = [],
4
i = 0;
5
6
while (copy.length)
7
output.push(copy.splice(0, rules[i++] ?? size))
8
9
10
return output
11
}
12
and it works fine if I have rules like { 0: 2, 1: 2 }
JavaScript
1
5
1
const input = [[1,2,3],[4,5,6,7]],
2
output = conditionalChunk(input.flat(), 3, { 0: 2, 1: 2 });
3
4
// OUTPUT: [[1,2],[3,4],[5,6,7]]
5
but when I have rules at the end like { 0: 2, 1: 2, 2:0, 5:0 } my function ignore to create empty arrays at the end.
the output I need is:
JavaScript
1
5
1
const input = [[1,2,3],[4,5,6,7]],
2
output = conditionalChunk(input.flat(), 3, { 0: 2, 1: 2, 2:0, 5:0 });
3
4
// OUTPUT: [[1,2],[3,4],[],[5,6,7],[]]
5
so I just need to not ignore rules for empty arrays at the end of array. How I can do that?
Advertisement
Answer
Finally, you could check the keys of rules
and if greater or equal to the next index of output
push an empty array.
JavaScript
1
17
17
1
function conditionalChunk(array, size, rules = {}) {
2
let output = [],
3
i = 0;
4
5
while (i < array.length)
6
output.push(array.slice(i, i += rules[output.length] ?? size));
7
8
let l = Object.keys(rules).reduce((l, v) => l + (v >= output.length), 0);
9
10
while (l--) output.push([]);
11
12
return output;
13
}
14
15
console.log(conditionalChunk([1, 2, 3, 4, 5, 6, 7], 3, { 0: 2, 1: 2 })); // [[1,2],[3,4],[5,6,7]]
16
console.log(conditionalChunk([1, 2, 3, 4, 5, 6, 7], 3, { 0: 2, 1: 2, 2: 0, 5: 0 })); // [[1,2],[3,4],[],[5,6,7],[]]
17
console.log(conditionalChunk([1, 2, 3, 4, 5, 6, 7], 3, { 0: 0, 1: 2, 8: 0, 7: 0, 9:0, 20:0 }));
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }