How to count the number of each consecutive unique character of a string.
Case exampe:
// Function Name : CountUniqueChar()
// Input : String
// Output : Array Object [{k: v}]
// Example :
// Input : “aaaasssiia”
// output : [{“a”: 4}, {“s”: 3}, {“i”: 2}, {“a”: 1}]
Using matchAll() with a regular expression and map():
const count = (s) =>
[...s.matchAll(/(.)\1*/g)].map(([{length}, c]) => ({[c]: length}));
console.log(count('aaaasssiia'));
Use for loop to iterate over each character in a string and compare with next character to keep count of consecutive unique char.
const input = "aaaasssiia";
const countChar = (str) => {
const list = [];
let count = 1;
for (let i = 0; i < str.length; i++) {
if (str[i] === str[i + 1]) {
count++
} else {
const obj = {};
obj[str[i]] = count;
list.push(obj);
count = 1;
}
}
return list;
}
console.log(countChar(input))