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

279
Views
How to find similar elements of string

I have stucked with a simple task and don't understand how to make the decision about it. There is one condition - do not use regular expressions. The task is to write a function that counts similar elements of a string so if we have dddmmmmccccaaamm, the function returns d3m4c4a3m2. Firstly I thought about converting string to array and using filter method but it is the wrong way. Now I think to find the first element of the array and compare it with each element in the loop, but don't know what to do next.

Please note, that my question doesn't match Count the number of occurrences of a character in a string in Javascript

function countFig(str) {
  let arr = str.split('');
  let newArr = [];
  let a = arr[0];
  let sum = 0;
  for (let i = 0; i < arr.length; ++i) {
    if ((i = arr.indexOf(a, i)) === -1) break;
    newArr.push(i); // here Im stucked
  }
  return newArr
}
console.log(countFig('dddmmmmccccaaamm'))

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could reduce each character and keep track of previous and count. You can initialize your reducer with the first character and increment the count each time you see consecutive occurrences.

If you run into a character that differs from the previous, reset the count, set the last to the curr, and append to the result.

I added the \b (backspace escape character) to the end of the array so that it can finish reducing the final sequence of characters. Left-over characters would be thrown away at the end. Now we can return the result portion of the reduction.

const countFig = (str) =>
  (([head, ...tail]) =>
    tail.reduce((acc, curr) =>
      curr === acc.last
        ? { ...acc, count: acc.count + 1 }
        : {
            ...acc,
            result: acc.result + acc.last + (acc.count + 1),
            last: curr,
            count: 0
          },
    {
      last: head,
      count: 0,
      result: ''
    }))
  ([...str.split(''), '\b']).result;

console.log(countFig('dddmmmmccccaaamm')); // d3m4c4a3m2
console.log(countFig('abbcccd'));          // a1b2c3d1

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!