javascript - 如何获取数组中所有连续数字的范围(递增子序列)?

标签 javascript ruby

在 ruby​​ 中,我可以这样使用 chunk_while:

a = [1,2,4,9,10,11,12,15,16,19,20,21]
b = a.chunk_while {|i, j| i+1 == j }
p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]

在 JavaScript 中执行此操作的最佳方法是什么?

最佳答案

您可以使用 Array.reduce() 创建一个 chunkWhile() 函数:

const chunkWhile = (predicate, arr) =>
  arr.reduce((r, n) => {
    let last = r[r.length - 1]
    
    if(!last || !predicate(last[last.length - 1], n)) {
      last = []
      r.push(last)
    }
    
    last.push(n)
    
    return r
  }, [])

const a = [1,2,4,9,10,11,12,15,16,19,20,21]

const result = chunkWhile((i, j) => i + 1 === j, a)

console.log(result)

关于javascript - 如何获取数组中所有连续数字的范围(递增子序列)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59636978/

相关文章:

javascript - Stripe - 不是充值卡

javascript - 不同按钮的切换功能

javascript - 使简单指令仅模态动态

javascript - jQuery : Use an alternative to . toggle() 已弃用

ruby-on-rails - 加载错误 : Unable to autoload constant (Rails + Sidekiq)

ruby - 如何清理哈希和数组混合的数据?

javascript - 子域中未加载 CSS 和 JS

javascript - Angularjs 与 css3 动画

ruby-on-rails - SASS 不会在 Sublime Text 2 中构建 [Errno 2] No such File or Directory

ruby - 在 Ruby 中跳过额外的关键字参数