Pratik Gaikwad Pratik Gaikwad - 1 month ago 4x
Javascript Question

Typescript Check if "any n consecutive elements are same" in M size array

I've an array of strings or numbers of size M(M>n). I want to check if any n consecutive elements are same where n can vary between 1-M.

For instance, let assume I've below array, and I want to check there are four consecutive '5's or two consecutive '3's are present or not:


How can I achieve this?

P.S. I'm also using Linq.JS to perform linq functions on array.


You might do as follows

var arr = [1,2,3,4,5,5,5,5,2,6,3,3,1],
 result = arr.reduce((p,c,i,a) => c !== a[i+1] ? (p[p.length-1][0] = c, p.concat([[0,1]]))
                                               : (p[p.length-1][0] = c, p[p.length-1][1]++, p),[[true,1]])