Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda