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

153
Visualizações
Convert string into an object using reduce javascript

I am trying to convert a string like "sheep" into an object like this:

{
   "s":{
      "initial":1,
      "final":1
   },
   "h":{
      "initial":1,
      "final":1
   },
   "e":{
      "initial":2,
      "final":2
   },
   "p":{
      "initial":1,
      "final":1
   }
}

Currently I can use reduce method in javascript and achive this:

const names = 'sheep'.split('');
const count = (names) =>
  names.reduce((acc, name) => ({ ...acc, [name]: (acc[name] || 0) + 1 }), {});
console.log(count(names)) //{ s: 1, h: 1, e: 2, p: 1 }

I have tried to read similar posts but I am pretty new to JS. Can anyone please help me? Thanks.

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

0

This works printing your desired output but I'm not sure why you want the initial and final counts to be the same

const letters = 'sheep'.split('');
const count = (letters) =>
  letters.reduce((obj, letter) => ({ ...obj, [letter]: {initial: (obj[letter]?.initial || 0) + 1, final: (obj[letter]?.final || 0) + 1} }), {});
console.log(count(letters)) 

Alternatively, you could expand a function there using braces and do some if's in order to have the code more readable instead of the ternaries

about 4 years ago · Juan Pablo Isaza Relatório

0

Try like this

const names = "sheep".split("");
const count = (names) =>
  names.reduce(
    (acc, name) => ({
      ...acc,
      [name]: {
        initial: (acc?.[name]?.initial ?? 0) + 1,
        final: (acc?.[name]?.final ?? 0) + 1,
      },
    }),
    {}
  );
console.log(count(names)); 

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