Find longest occurrence of same number in array

前端 未结 12 1502
一生所求
一生所求 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 17:52

    I've modified your function slightly. You need to store the highest streak as a separate variable from the current streak, and overwrite that where necessary in your loop - finally returning that variable at the end of your function.

    function streak(arr) {
        var i,
            temp,
            streak,
            length = arr.length,
            highestStreak = 0;
    
        for(i = 0; i < length; i++) {
            // check the value of the current entry against the last
            if(temp != '' && temp == arr[i]) {
                // it's a match
                streak++;
            } else {
                // it's not a match, start streak from 1
                streak = 1;
            }
    
            // set current letter for next time
            temp = arr[i];
    
            // set the master streak var
            if(streak > highestStreak) {
                highestStreak = streak;
            }
        }
    
        return highestStreak;
    }
    
    var array = [2,5,3,1,1,1,3,7,9,6,4,1,1,1,1,1,4,7,2,3,1,1,4,3];
    
    console.log(streak(array)); // 5
    

    And if you want to also track what the value of the highest streak was, define another variable at the start of your function, save the value of it when you save the highest streak, and return it as an array:

        // set the master streak var
        if(streak > highestStreak) {
            highestStreakValue = temp;
            highestStreak = streak;
        }
    }
    
    return [highestStreak, highestStreakValue];
    
    
    var array = [2,5,3,1,1,1,3,7,9,6,4,'a','a','a','a','a',4,7,2,3,1,1,4,3];
    console.log(streak(array)); // [5, "a"]
    

    Demo returning both

提交回复
热议问题