I have the following two arrays:
var arr1 = [1,2,4,5];
var arr2 = [];
How would I go about to split it when there is no consecutive value?
In this example, it should be split into: [
[1,2]
and [4,5]
.
These two arrays should be stored in arr2.
Example 2 :
var arr3 = [1,2,3,5,6,7,8,9,10,11,13]
Result : [[1,2,3], [5,6,7,8,9,10], [11], [13]]
I have the following two arrays:
var arr1 = [1,2,4,5];
var arr2 = [];
How would I go about to split it when there is no consecutive value?
In this example, it should be split into: [
[1,2]
and [4,5]
.
These two arrays should be stored in arr2.
Example 2 :
var arr3 = [1,2,3,5,6,7,8,9,10,11,13]
Result : [[1,2,3], [5,6,7,8,9,10], [11], [13]]
You could use Array#reduce
and check if the element is consecutive. Then append to the last array, otherwise push a new array to the result set.
var array = [1, 2, 4, 5],
result = array.reduce(function (r, a, i, aa) {
if (!i || aa[i - 1] + 1 !== a) {
r.push([a]);
} else {
r[r.length - 1].push(a);
}
return r;
}, []);
console.log(result);
Here is a way to do it :
var arr1 = [1,2,4,5];
var slices = [];
var sliceNb = 0;
arr1.forEach(function(v, k, arr){
if(!slices[sliceNb]){
slices[sliceNb] = [];
}
slices[sliceNb].push(v);
if(arr[k+1] && arr[k+1] > v+1){
sliceNb++;
}
});
console.log(slices);
try this:
arr1 = [1,2,3,4]
new_arr = [arr1.slice(0, (arr1.length/2) ), arr1.slice(arr1.length/2 +1, arr1.length)]
new_arr
//[[1,2],[3,4]]
You can figure out the chunk size my dividing the size of the array by the number of partitions. Then you can simply slice the array.
var arr1 = [1, 2, 4, 5];
var arr2 = partitionArray(arr1, 2); // [[1, 2], [4, 5]]
document.body.innerHTML = '<pre>arr2 = ' + JSON.stringify(arr2) + '</pre>';
/**
* Partitions an array into chunks.
* @param {Array} arr - The array to partition.
* @param {int} n - The number of partitions.
* @return {Array} Returns a partitioned array.
*/
function partitionArray(arr, n) {
var chunkSize = Math.max(arr.length / n, 1);
return [].concat.apply([], arr.map(function(item, i) {
return i % chunkSize ? [] : [arr.slice(i, i + chunkSize)];
}));
}
You might do as follows;
var arr = [1,2,4,5,6,111,111,112],
res = arr.reduce((p,c,i,a) => c === a[i-1]+1 ? (p[p.length-1].push(c),p)
: p.concat([[c]]),[]);
console.log(res);