You could sort the array, if not in ascending order and then reduce this array by checking the actual value and the predecessor.(您可以对数组进行排序(如果不按升序排列),然后通过检查实际值和前一数组来缩小该数组。)
If the dela is greater or equal 5
or if youi got the first value of the array, then push an empty array to the result set.(如果dela大于或等于5
或者您获得了数组的第一个值,则将空数组推入结果集。)
Then push the value to the last array in the result set.(然后将值推到结果集中的最后一个数组。)
var array = [1, 15, 16, 33, 35, 37, 55, 58], result = array .sort((a, b) => a - b) // not necessary with sorted data .reduce((r, v, i, a) => { if (!i || v - a[i - 1] >= 5) r.push([]); r[r.length - 1].push(v); return r; }, []); console.log(result);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…