- Trending Categories
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
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).
Example
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));
Output
And the output in the console will be −
3
Advertisements