For example I have an array:
const array= ['a', 'X', 'c', 'X', 'e', 'f', 'X']
And I want to split the array at each point where the element = X, so I should have 6 arrays afterwards:
['a'],
['X'],
['c'],
['X'],
['e', 'f'],
['X']
For example I have an array:
const array= ['a', 'X', 'c', 'X', 'e', 'f', 'X']
And I want to split the array at each point where the element = X, so I should have 6 arrays afterwards:
['a'],
['X'],
['c'],
['X'],
['e', 'f'],
['X']
If there's a character (or sequence of characters) (e.g. for the purpose of my demo code, #) that will not occur in the values, you can join the array using that character sequnce, then split on X (using a regex with capture group to retain the X values) and then split on the character sequence again:
const array = ['a', 'b', 'X', 'cd', 'X', 'e', 'f', 'X']
let out = array
.join('#') // merge into a string
.split(/(?:^|#)(X)(?:#|$)/) // split on X (but retain them)
.filter(Boolean) // remove empty values
.map(v => v.split('#')); // split on #
console.log(out);
#). Joining on an empty string has the same result without having to worry about picking something that doesn't appear in the arrayarray.join('').split(/(X)/).filter(Boolean).map(s => [...s])['ab', 'X', 'cd', 'X', 'e', 'f', 'X'] then without the join character you get [ [ "a", "b" ], [ "X" ], [ "c", "d" ], [ "X" ], [ "e", "f" ], [ "X" ] ](?:^|#) instead of # in case an X was the first entry in the array)use the temporary window to maintain the items in between separator.
const array = ["a", "X", "c", "X", "e", "f", "X", "n"];
const split = (arr, sep) => {
const output = [];
const win = [];
arr.forEach((item) => {
if (item === sep) {
output.push([...win], [item]);
win.length = 0;
} else {
win.push(item);
}
});
if (win.length > 0) {
output.push([...win]);
}
return output;
};
console.log(split(array, "X"));
indexOf starting from last found X position to get chunk, push sliced chunks and ['X']
let array = ['a', 'X', 'c', 'X', 'e', 'f', 'X']
const chunkX = array => {
if(!array.length) return array
let i = 0, j
const arr = []
while((j = array.indexOf('X',i)) !== -1) {
// i!==j to prevent generating blank array when two consecutive 'X's
i!==j && arr.push(array.slice(i,j))
arr.push([array[j]])
i = j + 1
}
if(i < array.length) arr.push(array.slice(i))
return arr
}
console.log(JSON.stringify(chunkX(array)))
// additional test cases that were failing
array = ['a','X','b','X','X','X','X', 'c', 'X', 'e', 'f', 'X', 'g']
console.log(JSON.stringify(chunkX(array)))
array = ['X','X','a','X','b','X','XX','X', 'c', 'X', 'e', 'f', 'X', 'g', 'X']
console.log(JSON.stringify(chunkX(array)))
array = ['X']
console.log(JSON.stringify(chunkX(array)))