How to count the number of each consecutive unique character of a string in javascript

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

Answer

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