Shiny Diamond
Shiny Diamond

Reputation: 105

Javascript - Group array of objects by array of keys

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;
}, {});

Upvotes: 1

Views: 73

Answers (1)

Barmar
Barmar

Reputation: 780974

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;
}, {});

Upvotes: 3

Related Questions