如何使用javascript分隔主组数组中的每个子组

时间:2018-09-07 09:31:23

标签: javascript arrays

我有一个数组。它包含几个子组。示例:

let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]

我想将该主数组划分为子数组。例如

sub1 =[50,51,52,53,54]
sub2 =[511,512,513,514]
sub3 =[521,522,523,524,525,526,527]

你能帮我吗?

4 个答案:

答案 0 :(得分:2)

这将创建一个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)

答案 1 :(得分:2)

使用Array reduce函数:

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);

答案 2 :(得分:1)

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);

答案 3 :(得分:0)

这是使用Ramda.js的解决方案

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>