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

100
Views
Find unique characters in a string and the count of their occurrences

I need to count the occurrence of characters in a given string and print out the unique characters and the number of how many times they appeared. So, for example, if I receive a string of 'HELLO' it should print out:

H: 1, E: 1, L: 2, O: 1

This is a much-simplified version of a problem, but the answer should put me in the right direction. How can I approach this problem?

Thank you in advance.

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

0

This is more or less what it should look like in order to make it easier it prints it in JSON you can already convert it to String yourself if you want.

function count_occurrence(text = "") {
    const array_from_text = text.split("");
    const result = {};
    Array.from(new Set(array_from_text)).forEach(word => {
        const { length } = array_from_text.filter(w => w === word);
        result[word] = length;
    });
    return result;
};
const occurences = count_occurence("HELLO");
console.log(occurences); // {H: 1, E: 1, L: 2, O: 1}
about 4 years ago · Juan Pablo Isaza Report

0

const countChars = (str) => {
  const charCount = {} ;
  for (const c of [...str]) {
    charCount[c] = (charCount[c] || 0) + 1 ;
  }
  return charCount ;
}
console.log(countChars('HELLO')) ; // {H: 1, E: 1, L: 2, O: 1}
about 4 years ago · Juan Pablo Isaza Report

0

You could use Array.reduce() to get a count of each occurrence in the input word.

We convert the word to an array using the ... operator, then .reduce() to create an object with a property for each unique letter in the word.

const input = 'HELLO';
const result = [...input].reduce((acc, chr) => { 
    acc[chr] = (acc[chr] || 0) + 1;
    return acc;
}, {});

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

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!