且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript将具有连续数字序列的数组中的数字分组

更新时间:2021-08-17 09:20:14

使用 Array#reduce 进行迭代,并且每当最后一个数字不等于新数字-1时,添加另一个子数组.将当前数字添加到最后一个子数组:

Iterate with Array#reduce, and whenever the last number is not equal to the new number - 1, add another sub array. Add the current number to the last sub array:

const a = [0,1,2,5,6,9];

const result = a.reduce((r, n) => {
  const lastSubArray = r[r.length - 1];
  
  if(!lastSubArray || lastSubArray[lastSubArray.length - 1] !== n - 1) {
    r.push([]);
  } 
  
  r[r.length - 1].push(n);
  
  return r;  
}, []);

console.log(result);