N consecutive odd numbers JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers as the first argument, and a number, say n, as the second argument.

The function should return true if there exist n consecutive odd numbers in the array, false otherwise.

For example − 

If the input array and number are −

const arr = [3, 5, 3, 5, 4, 3];
const n = 4;

Then the output should be true because first four numbers are all odd.

Example

const arr = [3, 5, 3, 5, 4, 3];
const n = 4;
const allOdd = (arr = [], n = 0) => {
   if(!arr.length){
      return;
   };
   let streak = 0;
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(el % 2 === 0){
         streak = 0;
      }
      else{
         streak++;
      };
      if(streak === n){
         return true;
      }
   };
   return false;
};
console.log(allOdd(arr, n));

Output

This will produce the following output −

true
raja
Published on 25-Nov-2020 05:30:59
Advertisements