Javascript将数组中的数字与一系列连续数字分组 [英] Javascript group the numbers from an array with series of consecutive numbers

查看:26
本文介绍了Javascript将数组中的数字与一系列连续数字分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如给定一个已排序的整数数组

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

我想确定范围,如

<预><代码>[[0,1,2],[5,6],[9]]

到目前为止,我已经尝试了双重/三重循环,但它嵌套了非常讨厌的代码.也许这个问题可以使用递归或其他聪明的技巧来解决?

<小时>附加示例:

输入

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

输出

<预><代码>[[0,1],[5,6,7],[9]]

解决方案

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

这篇关于Javascript将数组中的数字与一系列连续数字分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆