Question

I have an array like

var arr = [12, 13, 14, 17, 18, 19, 20]

I was wondering how I could iterate through the array so that I can split this array into 2 arrays based on the sequences ? i.e. basically if i+1 != true make it a new array

var arr = [12, 13, 14]
var arr2 = [17,18,19,20]

I am using lodash and have tried a number of for statements using splice but Im getting a bit confused ? Appreciate any help

Was it helpful?

Solution 2

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.

OTHER TIPS

Example on jsFiddle

var a = [1, 2, 3, 5, 6, 7];

var r = [];
var t = [];

for (var i = 0; i < a.length; ++i)
{
    if (i == 0)
    {
        t.push(a[i]); // add the first element and continue
        continue;
    }
    if (a[i - 1] != (a[i] - 1))
    {
        // if the current is not sequential
        // add the current temporary array to arrays result
        r.push(t);

        // clear the temporary array and start over
        t = [];
    }

    t.push(a[i]);
}
r.push(t);

r will contain all your arrays

Minified version

function seq(e,t,n,r){t=[];n=[];for(r=0;r<e.length;++r){if(!r){n.push(e[r]);continue}if(e[r-1]!=e[r]-1){t.push(n);n=[]}n.push(e[r])}t.push(n);return t}

var result = seq([1, 2, 3, 5, 6, 7]);

Do you mean like this?

function split(arr) {
    var res = [];
    var subres = [];
    for (var i = 0; i < arr.length; i++) {
        var length = subres.length;
        if (length === 0 || subres[length - 1] === arr[i] - 1) {
            subres.push(arr[i]);
        } else {
            res.push(subres);
            subres = [arr[i]];
        }
    }
    res.push(subres);
    return res;
}

try this :)

var array = [12,13,14,4567,789,0]; //e.g.
var index;
var previous = array[0];
for (var index = 1; index++; index < array.length) {
  if (previous + 1 == array[index]) {
    previous = array[index]; //++
  } else {
    break;
  }
}
var firstPart = array.slice(0, index + 1);
var secondPart = array.slice(index + 1);

http://jsfiddle.net/zajnH/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top