Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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']
        }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading