且构网

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

Javascript将数组中的数字与一系列连续数字分组

更新时间:2022-12-29 19:19:35

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

const a = [0,1,2,5,6,9];const 结果 = 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);返回 r;}, []);console.log(result);

Given a sorted array of ints for example

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

I would like to identify the ranges like

[
    [0,1,2],
    [5,6],
    [9]
]

So far I have tried a double/triple loop but it nests to really nasty code. Maybe this problem can be solved using recursion or other smart tricks?


Additional example:

input

b = [0,1,5,6,7,9];

output

[
    [0,1],
    [5,6,7],
    [9]
]

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