Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  135] [ 4]  / answers: 1 / hits: 10836  / 10 Years ago, fri, may 16, 2014, 12:00:00

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:
[2,5,3,1,1,1,3,7,9,6,4,1,1,1,1,1,4,7,2,3,1,1,4,3]



I'd like to write a function that would return 5, since the number 1 occurs 5 times in a row. (It also occurs 3 and 2 times in a row, but I'm after the longest occurrence).



So far, I have written:



function streak(arr) {
var i,
temp,
streak,
length = arr.length;

for(i=0; i<length; i++) {
if (arr[i] === 1) {
streak += 1;
} else {
temp = streak;
break;
}
}
}


I know I need some way of knowing where I left off if I find an occurrence, but I'm feeling kind of stuck.



Any pointers?


More From » arrays

 Answers
4

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


[#45267] Wednesday, May 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;