1

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!

Le Sparte
  • 163
  • 2
  • 12

1 Answers1

10

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));
llama
  • 2,535
  • 12
  • 11
  • Thank you very much llama. I really appreciate the ES6 flavour! :) – Le Sparte Oct 22 '17 at 13:16
  • @LeSparte, but it's a little slower… –  Oct 22 '17 at 13:27
  • @LeSparte: You're welcome. – llama Oct 22 '17 at 13:41
  • @llama, I'v tried to write the same code in ES5, but can't get it to work. I have an Uncaught TypeError. Any idea? streaks = tab.reduce(function(res,n){ if(n){ res[res.length-1]++; } else{ res.push(0); res; } }, [0]); – Le Sparte Oct 23 '17 at 09:36
  • 1
    @LeSparte: I updated the answer with an ES5 version. You needed only to have an explicit `return res;`, and it should be outside the `else` block. – llama Oct 23 '17 at 15:03