1

I have this problem, I want to group array of objects, each containing type array, into object of arrays.

Start:

const start = [
    { name: "Banana", type: ['fruit'] },
    { name: 'Apple', type: ['fruit', 'food'] }, 
    { name: 'Carrot', type: ['vegetable', 'food'] }
 ]

Desired result

  const desiredResult = {
    'fruit':[
      { name: "Banana", type: ['fruit'] },
      { name: 'Apple', type: ['fruit', 'food'] }
    ],
    'food': [
        { name: 'Apple', type: ['fruit', 'food'] },
        { name: 'Carrot', type: ['vegetable', 'food'] }
     ],
     'vegetable':[
         { name: 'Carrot', type: ['vegetable', 'food'] }
     ]
  };

Where I am stuck, not sure how to now map that type array :D Currently just have a.type[0], which is bad.

const groupedData = start.reduce(function (r, a) {
   r[a.type[0]] = r[a.type[0]] || [];
   r[a.type[0]].push(a);
   return r;
}, {});
1
  • Do the grouping (.push()) "for each" type (and clone the object if you need an actual copy of the object). Commented Apr 1, 2021 at 10:33

1 Answer 1

3

You need to loop over all the elements of a.type.

const groupedData = start.reduce(function(r, a) {
  a.type.forEach(type => {
    r[type] = r[type] || [];
    r[type].push(a);
  });
  return r;
}, {});

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

Comments

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.