Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda