1

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']
        }
2
  • Can you post the expected output?\ Commented Feb 1, 2022 at 15:06
  • Does this answer your question? Group array items using object Commented Feb 1, 2022 at 15:06

2 Answers 2

1

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

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

4 Comments

This question has been asked and answered many times; we don't need more answers to the same question.
@HereticMonkey appreciate that
thanks this question has not been asked by reduce()
It's been solved by reduce many time @Victor.
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
  }
}, {});

2 Comments

With the explanation, "What you can do is", which is not useful to anyone.
the code is pretty much self explanatory if you know how to use reduce. -_-

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.