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

176
Visualizações
Is it possible to use reduce with strings in JavaScript?

I wanted to know is it possible to use the reduce method on arrays with strings as well?

For ex: If I have an array like this: [ 'm', 'o', 'o', 'n' ] then I can reduce it to an object like this: { m: 1, o: 2, n: 1 }, that counts the occurrences of all characters in the string.
But if instead I had a string "moon" I wouldn't be able to use the reduce method with it.

I know I can write a custom implementation for reduce, but is there something simpler?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Yes, since Array.prototype.reduce is a generic method, it doesn't require it's this value to necessarily be an array. Meaning reduce is designed not only to work with arrays but to also work with other array-like values like strings.

And in order to use reduce with the string str, you can invoke it on the string by using Function.prototype.call.

const str = "moon";
const strCharCount = Array.prototype.reduce.call(
  str,
  (r, s) => {
    r[s] = (r[s] ?? 0) + 1;
    return r;
  },
  {}
);

console.log(strCharCount);

And if all of that didn't make any sense, you can also transform the string to an array and use reduce as you normally would.

const str = "moon";
const strCharCount = Array.from(str).reduce((r, s) => {
  r[s] = (r[s] ?? 0) + 1;
  return r;
}, {});

console.log(strCharCount);

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