To efficiently navigate through the array, it is crucial to analyze its values, limiting the solution to O(n) complexity. A practical approach involves iterating over the array while tracking the number of zeros encountered up to a certain point.
The following function offers a quick implementation of this strategy. It includes a variable for storing the previous index as well. Though the previous index could be inferred from the split array, doing so with large arrays might prove inefficient.
function divideArray(array, threshold) {
var zeros = 0,
previousIdx = 0,
dividedArrays = [];
array.forEach(function(element, index) {
if (element === 0) {
zeros++;
if (zeros == threshold && previousIdx != index - threshold + 1) {
dividedArrays.push(array.slice(previousIdx, index - threshold + 1));
previousIdx = index - threshold + 1;
}
} else if (zeros >= threshold) {
dividedArrays.push(array.slice(previousIdx, index));
previousIdx = index;
zeros = 0;
}
});
if (previousIdx != array.length - 1) {
dividedArrays.push(array.slice(previousIdx));
}
return dividedArrays;
}
A demonstration of this function's functionality using test data can be found on JSFiddle: https://jsfiddle.net/UniqueUser/examplelink123/
This code may still have room for further enhancements.
If your objective is solely to obtain section indices rather than splitting the array into separate arrays with data, you can replace the three occurrences of array.slice(a, b)
with [a, b-1]
.