I have an Array. It contains several subgroups. Example:
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
I want
var arr = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
var result = [],
lastVal = -1;
while(arr.length) {
var currentIndex = arr.length - 1;
var currentValue = arr[currentIndex];
var c = Math.floor(currentValue/10);
if (c !== lastVal) {
lastVal = c;
result.push([currentValue]);
}else{
result[result.length-1].push(currentValue);
}
arr.splice(currentIndex, 1);
}
result.forEach(function(arr){ arr.reverse(); });
console.log(result);
const x = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
const f = R.pipe(
R.sortBy(R.identity),
R.groupWith(R.pipe(R.subtract, Math.abs, R.equals(1)))
)
console.log(f(x))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
Use the Array reduce function :
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
let groups = mainArray.reduce (
(grps, el, i, main) => ((el === main[i-1] + 1 ? grps[0].push (el)
: grps.unshift ([el])), grps), []);
[sub3, sub2, sub1] = groups;
console.log (sub1, sub2, sub3);
This will create an Array of Subarays:
const arr = [50,51,52,53,54, 511,512,513,514, 521,522,523,524,525,526,527];
let newArr = [];
let temp = [arr[0]];
for (let index = 1; index < arr.length; index++) {
if (arr[index] == arr[index - 1] + 1) {
temp.push(arr[index]);
} else {
newArr.push(temp);
temp = [];
}
if (index == arr.length - 1) {
newArr.push(temp);
}
}
console.log(newArr)