- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements