Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sequence of equal numbers in array

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading