JSFiddle - React, Tailwind, and code Playground
by Marco Abate
JavaScript
const arr = ['a','a','b','a','a','a','a','b','a','a','a'];
let lastIndex = 0;
const cunked = arr.reduce((accumulator, currentValue, index) => {
if(accumulator.length) {
const lastChunkIndex = accumulator.length - 1;
const accumulatorLastChunk = accumulator[lastChunkIndex];
if(accumulatorLastChunk.length) {
const lastElementIndex = accumulatorLastChunk.length - 1;
const lastChunkElement = accumulatorLastChunk[lastElementIndex];
if(lastChunkElement === 'b') {
return [
...accumulator,
[currentValue]
]
}
return [
...accumulator.slice(0, lastChunkIndex),
[
...accumulatorLastChunk,
currentValue
]
]
} else {
return [
...accumulator.slice(0, lastChunkIndex),
[currentValue]
]
}
} else {
return [...accumulator, [currentValue]];
}
}, []);
console.log(cunked)