1

I want to get total count of consecutive repeated characters and numbers in a string. For example : const value = '11111aaaio222' So the output should be 11

Explanation:

"1" repeating 5 times

"a" repeating 3 times

"2" repeating 3 times

  • 2
    what have you tried so far? – kevinSpaceyIsKeyserSöze Dec 16 '22 at 07:29
  • you might try a regular expression with a back reference (https://stackoverflow.com/questions/15688193/how-to-find-3-or-more-consecutive-characters), or you could iterate through the string keeping a record of the last char to compare against, incrementing a count when it’s the same as current. – Dave Meehan Dec 16 '22 at 07:39

4 Answers4

1

You can achieve it using a simple regex as well. Following regex matches 2 or more consecutive repeated characters.

/(.)\1+/g

  • (.) - match any character
  • \1+ - match the previously matched character again one or more times

const regexp = /(.)\1+/g;
const str = '11111aaaio222';

const output = str.match(regexp).join('').length;

console.log(output)
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
0

const data = "11111aaaio222";

const result = Array.from(new Set([...data])).reduce((p, c) => {
    let tc = 0;
    [...data].forEach((ta, i) => {
        if (ta === c && data[i + 1] === c) tc++;
    })
    tc && (p += tc + 1);
    return p;
}, 0)

console.log(result);
Layhout
  • 1,445
  • 1
  • 3
  • 16
0

To calculate the number of repetitions you can use regex:

([a-zA-Z\d])\1*

It will return groups of values like this [11111, aaa, i, o, 222].

Now we need to go through the array with reduce and calculate the number of repeating elements. We also need to remove elements that are less than 2

const count = (str) => {
  const regex = /([a-zA-Z\d])\1*/g;
  const matches = str.match(regex) || [];
  return matches.reduce((acc, item) => {
    acc += item.length > 1 ? item.length : 0;
    return acc
  }, 0);
}

console.log(count("11111aaaio222"))

So we go through the array and sum up only those values that are repeated more than once.

current value: 0, item - 11111
current value: 5, item - aaa
current value: 8, item - i
current value: 8, item - o
current value: 8, item - 222
output value: 11
Pobepto
  • 430
  • 2
  • 8
-1

function duplicateCharCount(str) {
    if(str) {
        var obj = {};
        for(let i = 0; i < str.length; i++) {
            if(obj[str[i]]){
                obj[str[i]] += obj[str[i]];
            }else {
                obj[str[i]] = 1;
            }
        }
        console.log(obj);
    }
            
}

duplicateCharCount("aabcdd");

https://gist.github.com/msaxena25/62d17a1c9b1e507f2eafd83fc7d54db0

Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
Pamblo
  • 1
  • 1