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]
>Solution :
This can be achieved like so:
let arr = ['2', '1', '1', '2', '3', '3', '2', '2', '2', '1'].map(Number)
let maxSequence = [];
let currentSequence = [];
let currentValue = -1;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === currentValue) {
currentSequence.push(arr[i]);
} else {
currentValue = arr[i];
currentSequence = [currentValue];
}
if (currentSequence.length > maxSequence.length) {
maxSequence = currentSequence
}
}
console.log(maxSequence.length) // expected output: 3
console.log(maxSequence) // expected output: [2, 2, 2]