I have 2 arrays. one of them(config) decides how many elements are going to be pushed in new array(finalData) from existing array(items).
I tried to use slice but at the 3rd index the value is duplicated from the 2nd index. Try to run code and you'll get the idea. Here's my sandbox
Desired output is that I get an array of arrays split exactly by using config indexes.
const config = [1,2,1, 2];
const items = ["one", "two", "three", "four", "five", "six", "seven", "eight"];
const finalData = []
for (let i = 0; i < items.length; i++) {
if(config[i] !== undefined) {
finalData.push(items.slice(i, config[i] + i))
} else {
finalData.push([items[i]])
}
}
console.log(finalData);
.as-console-wrapper { max-height: 100% !important; }
[ ['one'], ['two', 'three'], ['four'] ... ]or[ ['one'], ['two', 'three'], ['three'] ... ]or something else? Your current code seems to output the second optionfor (let i = 0; i < items.length; i += config[i] ?? 1) {??slice(), you need to incrementiby that number of items.