Please consider this array:
let tab = [0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1]
What's the best way to get "5" as the longest streak with "1" values?
Many thanks for your help!
Please consider this array:
let tab = [0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1]
What's the best way to get "5" as the longest streak with "1" values?
Many thanks for your help!
You can use .reduce()
to create a new array that either gets a 0
when 0
is found, or increments the last item in it.
Then use Math.max
to find the greatest number.
let tab = [0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1];
let streaks = tab.reduce((res, n) =>
(n ? res[res.length-1]++ : res.push(0), res)
, [0]);
console.log(streaks.join(","));
console.log(Math.max(...streaks));
Here's an ES5 version of the code.
let tab = [0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1];
let streaks = tab.reduce(function(res, n) {
if (n) res[res.length-1]++;
else res.push(0);
return res;
}, [0]);
console.log(streaks.join(","));
console.log(Math.max.apply(Math, streaks));