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

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

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 Denunciar

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 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