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: 2020-08-28T14:05:02+05:30

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements