Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 Output
The output in the console will be −
4
2
Advertisements
