使用 underscore.js 对 javascript 中没有间隙的数字序列进行分组 [英] Grouping a sequence of numbers with no gaps in javascript using underscore.js
本文介绍了使用 underscore.js 对 javascript 中没有间隙的数字序列进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个数字数组[1, 2, 3, 4, 7, 8, 11, 15, 16, 17, 18]
,我们如何使用下划线.js.
Having an array of numbers [1, 2, 3, 4, 7, 8, 11, 15, 16, 17, 18]
, how can we group them in groups of consecutive numbers using underscore.js.
所以期望的输出是 4 组(1-4、7-8、11 和 15-18)[[1, 2, 3, 4], [7, 8], [11], [15, 16, 17, 18]]
So the desired output is 4 groups (1-4, 7-8, 11 and 15-18)
[[1, 2, 3, 4], [7, 8], [11], [15, 16, 17, 18]]
推荐答案
我只会用 reduce 来做,而不用担心另一个库.
I would just do it with reduce and not worry about another library.
[1, 2, 3, 4, 7, 8, 11, 15, 16, 17, 18].reduce((arr, val, i, a) => {
if (!i || val !== a[i - 1] + 1) arr.push([]);
arr[arr.length - 1].push(val);
return arr;
}, []);
var result = [1, 2, 3, 4, 7, 8, 11, 15, 16, 17, 18].reduce((arr, val, i, a) => {
if (!i || val !== a[i - 1] + 1) arr.push([]);
arr[arr.length - 1].push(val);
return arr;
}, []);
console.log(result);
这篇关于使用 underscore.js 对 javascript 中没有间隙的数字序列进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文