Home > front end >  Javascript - Count number of consecutive character occurrences
Javascript - Count number of consecutive character occurrences

Time:09-30

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]]

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'))

CodePudding user response:

You can use String.matchAll to match all the groups of characters in your string; then just iterate the matches to produce your desired result:

const str = 'aaaabccaadeeee'

const res = Array.from(str.matchAll(/(.)\1*/g)).map(([m, g]) => [m.length, g])

console.log(res)

CodePudding user response:

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'))

CodePudding user response:

Here is another way of doing it without RegExp:

const str="aaaabccaadeeee";

const res=[];
str.split("").reduce((a,c,i)=>{
 if(a!==c) res.push([0,c]);
   res.at(-1)[0];
 return c;
},null);
console.log(res);
// for comparison: Nick's solution:
console.log([...str.matchAll(/(.)\1*/g)].map(([m,g])=>[m.length,g]))

  • Related