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

Javascript – Count number of consecutive character occurrences

I have been trying to solve this problem for some time now and I have partially managed to achieve it.

I am trying to write a function that will return a nested array, each array element will contain the number of consecutive chars found in a given string.

For example: for the given string "aaaabccaadeeee", the function should return nested array
[[4, a] [1, b] [2, c] [2, a] [1, d][4, e]]

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

I have managed to write the following function but it returns
[ [ 4, ‘b’ ], [ 0, ‘c’ ], [ 1, ‘a’ ], [ 1, ‘d’ ], [ 0, ‘e’ ] ]

What am I doing wrong?

function consecutiveArray(str) {

  const chunks = str.split("");
  let counter = 0;
  const finalArray = [];
  let  prevItem;


  for(chunk of chunks){

    if(!prevItem || prevItem === chunk){
      counter++
    } else {
      finalArray.push([counter, chunk])
      counter=0;
    }

    
    prevItem = chunk;
  }

  

  return finalArray;
  
}


console.log(consecutiveArray('aaaabccaadeeee'))

>Solution :

Your else clause is wrong, you should push the counter for prevItem and initialize the count to 1. Also, push the final counter the after the loop.

function consecutiveArray(str) {
  const chunks = str.split("");
  let counter = 0;
  const finalArray = [];
  let  prevItem;
  for(chunk of chunks){
    if(!prevItem || prevItem === chunk){
      counter++
    } else {
      finalArray.push([counter, prevItem])
      counter=1;
    }
    prevItem = chunk;
  }
  finalArray.push([counter, prevItem])
  return finalArray;
}
console.log(consecutiveArray('aaaabccaadeeee'))
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