I have this array in JS
initialArray = [A,B,C,C,D,E,F,F,G,K]
I want to split into:
chucks = [[A,B,C], [C,D,E,F], [F,G,K]]
Duplicate items are separators such as 'C' or 'F'
How to do this split in ES6?
CodePudding user response:
You could reduce the array and add either the value or a new array, depending on the last value.
const
array = ['A','B','C','C','D','E','F','F','G','K'],
result = array.reduce((r, v, i, { [i - 1]: last }) => {
if (v === last) r.push([]);
else r[r.length - 1].push(v);
return r;
}, [[]]);
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Does this works for you?
const initialArray = ["A","B","C","C","D","E","F","F","G","K"];
const chunks = [];
for (let i = 0; i < initialArray.length; i = 3){
const chunk = [];
for (let x = i; x < i 3 && x < initialArray.length; x ){
chunk.push(initialArray[x]);
}
chunks.push(chunk);
}
console.log(chunks);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Fairly straight forward solution using a single for
loop and holding the current chunk in a variable to push to.
const initialArray = ['A', 'A', 'B', 'C', 'C', 'D', 'E', 'F', 'F', 'G', 'K', 'K'];
const chunk_at_duplicate = (arr) => {
let chunk = [], res = [chunk];
for (let i = 0; i < arr.length; i ) {
if (arr[i] === arr[i - 1]) {
res.push(chunk = []);
}
chunk.push(arr[i]);
}
return res;
};
console.log(chunk_at_duplicate(initialArray));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>