gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:36 28 4
gpt4 key购买 nike

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com