- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# Length of the longest possible consecutive sequence of numbers in JavaScript

We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.

The function should find and return the length of the longest consecutive increasing sequence that exists in the array (contiguous or non-contiguous).

For example −

If the input array is −

const arr = [4, 6, 9, 1, 2, 8, 5, 3, -1];

Then the output should be 6 because the longest consecutive increasing sequence is 1, 2, 3, 4, 5, 6.

## Example

Following is the code −

const arr = [4, 6, 9, 1, 2, 8, 5, 3, -1]; const consecutiveSequence = (arr = []) => { const consecutiveRight = {}; let max = 0; for (let i = 0; i < arr.length; i += 1) { let curr = arr[i]; if (consecutiveRight[curr] !== undefined) { continue; // We already have this number. consecutiveRight[curr] = 1 + (consecutiveRight[curr + 1] || 0); while (consecutiveRight[curr - 1] !== undefined) { consecutiveRight[curr - 1] = consecutiveRight[curr] + 1; curr -= 1; } max = Math.max(max, consecutiveRight[curr]); } return max; }; console.log(consecutiveSequence(arr));

## Output

Following is the console output −

6

- Related Articles
- Program to find length of longest consecutive sequence in Python
- Longest Consecutive Sequence in Python
- Find the Length of the Longest possible palindrome string JavaScript
- Binary Tree Longest Consecutive Sequence in C++
- Binary Tree Longest Consecutive Sequence II in C++
- Find the longest sub array of consecutive numbers with a while loop in JavaScript
- Program to find length of longest possible stick in Python?
- Longest string consisting of n consecutive strings in JavaScript
- Finding the longest "uncommon" sequence in JavaScript
- Sum of consecutive numbers in JavaScript
- Finding longest consecutive joins in JavaScript
- Length of longest string chain in JavaScript
- Finding the character with longest consecutive repetitions in a string and its length using JavaScript
- Find length of the longest consecutive path from a given starting characters in C++
- Program to find length of longest consecutive path of a binary tree in python

Advertisements