Find longest occurrence of same number in array

前端 未结 12 1530
一生所求
一生所求 2021-01-05 17:49

Using JavaScript, I\'m trying to find a way to find the longest occurrence of the same number (in this case, 1) in an array.

For instance, here\'s a sample array:

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-05 18:07

    Your problems:

    • You don't store current streak
    • You don't specify when streak is more then older streak

    Use this:

    function streak(arr) {
        var i,
            temp,
            streak = 1,
            maxStreak = 0,
            prevNumber,
            length = arr.length;
    
        for(i=1; i maxStreak) {
                    maxStreak = streak;
                    streak = 1;
                }
            }
        }
        return maxStreak;
    }
    

    Demo

提交回复
热议问题