Here's another, more dense approach that uses underlining quite conveniently groupBy and values :
var origin = [12,13,14,15,17,18,19,21,22,23]; var c = 0, result = _.values( _.groupBy(origin, function(el, i, arr) { return i ? c+= (1 !== el - arr[i-1]) : 0; }) );
As a result, the result archive will contain all sequences as elements. Here's the JSFiddle to play with.
Explanation: groupBy groups the source array using a callback (which returns a new sequence number each time when the difference between the current processed element ( el ) and the previous ( arr[i-1] ) is greater than 1. It returns an object, however, therefore I have to execute it through _.values , you may or may not complete this step.
I wonder if it is possible to request something like the function groupByInArray ? It should be trivial to implement, but can be very useful in such situations.
source share