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
-
Economics & Finance
How to find and return the longest repeating series of numbers in array with JavaScript
We are required to write a JavaScript function that takes in an array of Numbers that may contain some repeating elements. The function should return the length of the longest repeating number sequence from the array.
For example −
If the input array is −
const arr = [2, 1, 1, 2, 3, 3, 2, 2, 2, 1];
Then the output should be 3 because the number 2 is repeated 3 times consecutively in the array (and that's the highest number).
Using Array.reduce() Method
The reduce() method can be used to group consecutive identical elements and then find the longest sequence:
const arr = [2, 1, 1, 2, 3, 3, 2, 2, 2, 1];
const findLongestSequence = (arr = []) => {
const res = arr.reduce((acc, val, ind) => {
if (acc.length && acc[acc.length-1][0] === val) {
acc[acc.length-1].push(val);
} else {
acc.push([val]);
}
return acc;
}, []).reduce((acc, val) => {
return val.length > acc.length ? val : acc;
});
return res.length;
}
console.log(findLongestSequence(arr));
3
Using Simple Loop Approach
A more straightforward approach using a simple loop to track consecutive elements:
const arr = [2, 1, 1, 2, 3, 3, 2, 2, 2, 1];
const findLongestSequenceLoop = (arr = []) => {
if (arr.length === 0) return 0;
let maxLength = 1;
let currentLength = 1;
for (let i = 1; i < arr.length; i++) {
if (arr[i] === arr[i - 1]) {
currentLength++;
maxLength = Math.max(maxLength, currentLength);
} else {
currentLength = 1;
}
}
return maxLength;
}
console.log(findLongestSequenceLoop(arr));
3
How It Works
The first approach uses two reduce operations:
- First reduce groups consecutive identical elements into subarrays
- Second reduce finds the subarray with maximum length
- Returns the length of the longest sequence
The loop approach simply iterates through the array, counting consecutive identical elements and keeping track of the maximum count encountered.
Example with Different Input
const testArray = [1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3];
console.log("Array:", testArray);
console.log("Longest sequence length:", findLongestSequenceLoop(testArray));
Array: [1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3] Longest sequence length: 5
Comparison
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
| Array.reduce() | Complex | O(n) | Higher (creates subarrays) |
| Simple Loop | Clear | O(n) | Lower (constant space) |
Conclusion
Both approaches solve the problem effectively, but the simple loop method is more readable and memory-efficient. Use the loop approach for better performance and clearer code logic.
