want to get a count of repeated values on an array

Viewed 148

I am a beginner in javascript, I want to get a count of repeated values on an array

I have a string "aaaaaabbbbbbbcccccccaa" and I want the output array be like ["a6", "b7", "c7", "a2"];

I tied but failed. Please help me out

Thanks In Advance :)

var a = "aaaaaabbbbbbbcccccccaa";

function aa(data){
  var a = [];
  var x = [];
  //var b = data.split("")
//   var b = data.split("").filter((val,key, arr)=>{
//       //console.log(arr.indexOf(val) +" "+ key )
//       return arr.indexOf(val) === key
//   })
  //console.log(b);
  
  for(let i = 0; i<= data.length-1; i++){
    for(let j = 0; j<= data.length-1; j++){
     if(data[i] !== data[j] && x.indexOf(data[i]+""+j) <0){
       x.push(data[i]+""+j);
       a.push(data[i] +""+ j);
       break;
     }
    }
  }
  console.log(x);
  return a;
}

console.log(aa(a));

1 Answers

I'd use a regular expression to match repeated characters in the string, then map them to match[0] + match.length to get the concatenated substring for that portion:

const aa = data => data
  .match(/(.)\1*/g)
  .map(match => match[0] + match.length);
console.log(aa('aaaaaabbbbbbbcccccccaa'));

If you don't want to use a regular expression, don't use a nested loop like that from 0 to the string length - instead, count up repeated characters from inside the first loop, starting at the current i index and incrementing it:

function aa(data) {
  const result = [];
  for (let i = 0; i < data.length; i++) {
    const char = data[i];
    let matches = 1;
    while (data[i + 1] === char) {
      i++;
      matches++;
    }
    result.push(char + matches);
  }
  return result;
}

console.log(aa('aaaaaabbbbbbbcccccccaa'));

Related