Split arrays based on javascript sequences

I have an array like

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

I was wondering how can I go through an array so that I can split this array into 2 arrays based on sequences? those. 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 several for statements using splice , but Im a bit confused? Appreciate any help

+4
source share
4 answers

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.

+2
source

JsFiddle example

 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

Mini 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]); 
+1
source

Do you mean 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; } 
0
source

try the following :)

 var array = [12,13,14,4567,789,0]; //eg 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/

0
source

Source: https://habr.com/ru/post/1484070/


All Articles