Skip to content
Advertisement

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

Advertisement

Answer

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;
}, {});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement