I am currently exploring the most effective approach to divide an array into multiple arrays based on specific operations performed on the values within the array.
Imagine I have an array like this:
var arr = [100, 200, 300, 500, 600, 700, 1000, 1100, 1200]
I aim to separate this array into different arrays whenever the difference between elements exceeds 100.
The desired output would be:
var result = [[100, 200, 300], [500, 600, 700], [1000, 1100, 1200]]
What is the most efficient method to achieve this?
I have attempted using a traditional for loop with if conditions that check the difference between consecutive elements. Whenever the difference surpasses 100, a new array is created. However, I sense there could be a more optimized solution.
EDIT:-
This is the code snippet I have implemented. Although it is close, it is not yet complete. I did not invest further time as I was aiming to find a simpler version utilizing reduce or underscore -
var result = [], temp = [], difference;
for (var i = 0; i < array.length; i += 1) {
if (difference !== (array[i + 1] - array[i])) {
if (difference !== undefined) {
result.push(temp);
temp = [];
}
difference = array[i + 1] - array[i];
}
temp.push(array[i]);
}
if (temp.length) {
result.push(temp);
}