Determine groups in a string

Viewed 381

I am trying to determine groups in a string.

For example "AAABBCCCCD" should have ["AAA", "BB", "CCCC", "D"] as groups based on the pattern in the string.

Here is my simple function to do that:

const patternGroup = (str) => {
  let cursor = str[0]
  let groups = []
  let currentGroup = ""
  for (let i = 0; i < str.length; i++) {
    let ch = str[i]
    if (ch === cursor) {
      currentGroup += ch
    }
    else {
      groups.push(currentGroup)
      currentGroup = ch
      cursor = ch
    }
  }
  if (currentGroup !== "") {
    groups.push(currentGroup)
  }
  return groups
}

It works as intented but I am looking for a simpler function, maybe using map/reduce or regex. Any ideas?

3 Answers

you can simply use RegExp:

var input = "AAABBCCCCD";
const res = input.match(/([^])(\1*)/g);

console.log(res)

Similar to your implementation:

const patternGroupWithReduce = (str) => {
  let currentGroup = ""
  return str.split("").reduce((acc, cur, i) => {
    currentGroup += cur
    if (str[i + 1] !== cur) {
      acc.push(currentGroup)
      currentGroup = ""
    }
    return acc
  }, [])
}

const patternGroupWithRegex = (str) => {
  return str.match(/(.)\1*/g)
}

RegEx /(.)\1/g* uses the back reference for the capturing group.

\1* matches the same char as recently captured one as many times as possible.

Here is the visualization for it: enter image description here

You could use

(.)\1*

As in:

let string = "AAABBCCCCD";
let rx = /(.)\1*/g;
let parts = string.match(rx);
console.log(parts);

See a demo for the expression on regex101.com.

Related