Javascript将具有连续数字序列的数组中的数字分组 [英] Javascript group the numbers from an array with series of consecutive numbers
本文介绍了Javascript将具有连续数字序列的数组中的数字分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,给出一个排序的整数数组
Given a sorted array of ints for example
a = [0,1,2,5,6,9];
我想确定范围
[
[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?
附加示例:
输入
b = [0,1,5,6,7,9];
输出
[
[0,1],
[5,6,7],
[9]
]
推荐答案
使用 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);
这篇关于Javascript将具有连续数字序列的数组中的数字分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文