I want to push the first sequence to currentSequence, then store it in maxSequence, then push the next sequence in currentSequence, check if its length is greater, if it isn’t proceed further, if it is store it in maxSequence. I’d like to keep the original order of the array.
let arr = ['2','1','1','2','3','3','2','2','2','1'].map(Number)
let maxSequence = []
for(let i = 0; i< arr.length; i++){
let currentSequence = []
if( arr[i] === arr[i+1] ){
currentSequence.push(arr[i]);
//currentSequence = arr.toSpliced(i, 1);
}
if(currentSequence.length > maxSequence.length){
maxSequence = currentSequence
}
}
console.log(maxSequence.length) // expected output: 3
console.log(maxSequence) // expected output: [2, 2, 2]
3
Answers
This can be achieved like so:
One way of doing what you need is:
Can be done without an intermediate array.