Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
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}]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Using matchAll() with a regular expression and map():

const count = (s) =>
    [...s.matchAll(/(.)\1*/g)].map(([{length}, c]) => ({[c]: length}));

console.log(count('aaaasssiia'));

about 4 years ago · Juan Pablo Isaza Report

0

You can simple achieve this using match and map using /(\w)\1*/g

enter image description here

const str = "aaaasssiia";
const result = str.match(/(\w)\1*/g).map((s) => ({ [s[0]]: s.length }));
console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!