javascript - 在 Javascript 数组中查找特定的连续数字集

标签 javascript

我想找出一个整数在数组中连续出现的次数。我发现一个例子在做类似的事情:

const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293];

let chunks = [];

let prev = 0;
numbers.forEach((current) => {
  if ( current - prev != 1 ) chunks.push([]);

  // Now we can add our number to the current chunk!
  chunks[chunks.length - 1].push(current);
  prev = current;
});

chunks.sort((a, b) => b.length - a.length);

console.log('Longest consecutive set:', chunks[0]);
console.log('Size of longest consecutive set:', chunks[0].length);

我只想得到0的最长连续数,比如:

result: {
  key: 0
  longestConsecutive: 5
}

有什么好的解决办法吗?谢谢!

最佳答案

您可以使用 Array.prototype.reduce为您的目标值创建一个序列长度数组,然后使用 Math.max获取该数组中的最大值(即最长序列的长度):

const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293];

function max_consecutive ( arr, value ) {
  return Math.max( ...numbers.reduce( (sequence_lengths, x) => {
      x === value ? sequence_lengths[0]++ : sequence_lengths.unshift(0);
      return sequence_lengths;
    }, [0]
  ) );
}

console.log( max_consecutive(  numbers, 0 ) );
console.log( max_consecutive(  numbers, 1 ) );
console.log( max_consecutive(  numbers, 293 ) );
console.log( max_consecutive(  numbers, 296 ) );

关于javascript - 在 Javascript 数组中查找特定的连续数字集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147608/

相关文章:

javascript - onblur 将文本复制到其他输入字段

javascript - D3 饼图过渡

javascript - 如何使用<td>值进行jquery计算代替&lt;input type ="number">

javascript - 将固定侧边栏右侧的 div 的宽度设置为剩余的 100% 视口(viewport)

javascript - JQuery 拉伸(stretch)按钮水平到窗口宽度

javascript - Highcharts - 缩放从 0 开始 Y 轴

javascript - 从普通对象创建类实例,无需手动构造函数

javascript - 在 Javascript 中移动(而不是卡住)日期/时间

javascript - 如何滚动到具有特定 div 类的第一个可见元素?

javascript - 使用回车键提交表单时遇到问题