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