我想找出一个整数在数组中连续出现的次数。我找到了一个相似的例子:
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
}
有什么好的解决方案吗?谢谢!
arr
作为参数,但在函数体中使用了numbers
。 - kbo