Here's a another, more dense approach, which uses underscore's quite convenient groupBy and values methods:
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, result
archive will contain all the sequences as elements. Here's the JSFiddle to play with.
Explanation: groupBy
groups the source array with help of the callback (which returns a new sequence number each time the difference between the currently processed element (el
) and the previous one (arr[i-1]
) is bigger than 1. It returns an object, though, so I have to put it through _.values
; you may or may not this step.
I wonder is that possible to request something like groupByInArray
function? Should be trivial to implement, but might be very useful in situations like this.