So the goal is to fragment an array to subarrays on the stumble of a certain element Example below for array.split("stop here")
["haii", "keep", "these in the same array but", "stop here", "then continue", "until you reach", "another", "stop here", "and finally", "stop here", "stop here"]
that to
[
["haii", "keep", "these in the same array but"], ["then continue", "until you reach", "another"], ["and finally"]
]
What I tried till now is not working very well:
Array.prototype.split = function (element) {
const arrays = [];
// const length = this.length;
let arrayWorkingOn = this;
for(let i=0; i<arrayWorkingOn.length; i++) {
if(this[i] === element) {
const left = arrayWorkingOn.slice(0, i);
const right = arrayWorkingOn.slice(i, arrayWorkingOn.length);
arrayWorkingOn = right;
arrays.push(left);
console.log(right);
}
}
arrays.push(arrayWorkingOn); //which is the last 'right'
return arrays;
}
Thanks in advance for your time and effort!
First .join() your arrays with an unique seperator in my case UNIQUE_SEPERATOR
Then you split it up first with .split("stop here") that returns you an array with 3 strings in it.
Now you need to .map() over the array and split it up by your seperator (UNIQUE_SEPERATOR) and .filter() out the "" values.
At the end you filter out the empty arrays by checking its length and you are done.
let arr = [
"haii",
"keep",
"these in the same array but",
"stop here",
"then continue",
"until you reach",
"another",
"stop here",
"and finally",
"stop here",
"stop here"
];
Array.prototype.split = function() {
return this.join("UNIQUE_SEPERATOR")
.split("stop here")
.map(el => el.split("UNIQUE_SEPERATOR").filter(Boolean))
.filter(arr => arr.length);
};
console.log(arr.split());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With