Skip to content
Advertisement

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.

Advertisement

Answer

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)); 
Advertisement