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

187
Views
how to create a key object and value in an array using reduce()

I have an array of objects, and I need to return an object where its key is the type of pet and its value is an array with the names of the pets. but I can't create the array of the names.

let pets=[
    {name:'kity', edad:10,type:'cat'},
    {name:'saske', edad:10,type:'dog'},
    {name:'naruto', edad:10,type:'dog'},
    {name:'goku', edad:10,type:'cat'},
    {name:'flofy', edad:10,type:'dog'},
    {name:'flufin', edad:10,type:'cat'},
    {name:'honey', edad:10,type:'bird'},
    {name:'silvestre', edad:10,type:'cat'},
    {name:'taz', edad:10,type:'dog'},
    {name:'piolin', edad:10,type:'bird'},
    {name:'gogeta', edad:10,type:'dog'},
]

const reduced = pets.reduce((acc, {name,type}) => ({
        ...acc, [`Type${type}`]: acc[...name]
        }), {});


        

expected

reduce ={
            Typecat:['kity','goku','flufin','silvestre'],
            Typedog:['saske','naruto','flofy','taz','gogeta'],
            Typebird:['honey','piolin']
        }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can do this:

let pets=[
  {name:'kity', edad:10,type:'cat'},
  {name:'saske', edad:10,type:'dog'},
  {name:'naruto', edad:10,type:'dog'},
  {name:'goku', edad:10,type:'cat'},
  {name:'flofy', edad:10,type:''},
  {name:'flufin', edad:10,type:'cat'},
  {name:'honey', edad:10,type:'bird'},
  {name:'silvestre', edad:10,type:'cat'},
  {name:'taz', edad:10,type:'dog'},
  {name:'piolin', edad:10,type:'bird'},
  {name:'gogeta', edad:10,type:'dog'},
];

const result = pets.reduce((acc, item) => {
  if(acc[`Type${item.type}`]) {
    acc[`Type${item.type}`].push(item.name);
  } else {
    acc[`Type${item.type}`] = [item.name];
  }
  return acc;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

What you can do is:

const result = pets.reduce((acc, item) => {
  const values = acc[item.type] ? acc[item.type].concat(item.name) : [item.name]
  
  return {
    ...acc,
    [item.type]: values
  }
}, {});
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!