Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!