2

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.

2
  • 3
    You are already pretty close, you just need to define the desired structure inside the reduce callback, but it is not clear what is the difference between initial and finalvalues. Can you elaborate on those? Commented Jan 28, 2022 at 13:08
  • I am going to modify the final count for my specific purpose. Sorry for using a simple example 😅 But the question has been answered. Thanks. Commented Jan 28, 2022 at 14:14

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

I am going to modify the final count for my specific purpose. Sorry for using a simple example 😅

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.