Find longest occurrence of same number in array

前端 未结 12 1524
一生所求
一生所求 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:14

    You could take Array#reduce and return the start index of the actual same item sequence. Then check and update the counter if the item is not equal.

    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],
        maxCount = 0,
        maxValues;
    
    array.reduce(function (j, a, i, aa) {
        if (aa[j] === a) {
            return j;
        }
        if (i - j === maxCount){
            maxValues.push(aa[j]);
        }            
        if (i - j > maxCount) {
            maxCount = i - j;
            maxValues = [aa[j]];
        }
        return i;
    }, -1);
    
    console.log(maxCount);
    console.log(maxValues);

提交回复
热议问题