Find the longest sub array of consecutive numbers with a while loop in JavaScript


We are required to write a function with a while-statement that determines the length of the largest consecutive subarray in an array of positive integers.

For instance −

If the input array is −

const input = [6, 7, 8, 6, 12, 1, 2, 3, 4] --> [1,2,3,4]

Then the output should be −

4

If the input array is −

const input = [5, 6, 1, 8, 9, 7] --> [8,9]

Then the output should be −

2

Therefore, let’s write the code for this function −

Example

const arr = [6, 7, 8, 6, 12, 1, 2, 3, 4];
const arr1 = [5, 6, 1, 8, 9, 7];
const findLongestSub = arr => {
   let count = 1, len = 0, max = 1;
   while(len < arr.length){
      if(arr[len] === arr[len - 1] + 1){
         count++;
         if(max < count){
            max = count;
         }
         }else{
            count = 1;
      };
      len++;
   };
   return max;
};
console.log(findLongestSub(arr));
console.log(findLongestSub(arr1));

Output

The output in the console will be −

4
2

Updated on: 28-Aug-2020

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements