I have this problem, I want to group array of objects, each containing type array, into object of arrays.
Start:
JavaScript
x
6
1
const start = [
2
{ name: "Banana", type: ['fruit'] },
3
{ name: 'Apple', type: ['fruit', 'food'] },
4
{ name: 'Carrot', type: ['vegetable', 'food'] }
5
]
6
Desired result
JavaScript
1
14
14
1
const desiredResult = {
2
'fruit':[
3
{ name: "Banana", type: ['fruit'] },
4
{ name: 'Apple', type: ['fruit', 'food'] }
5
],
6
'food': [
7
{ name: 'Apple', type: ['fruit', 'food'] },
8
{ name: 'Carrot', type: ['vegetable', 'food'] }
9
],
10
'vegetable':[
11
{ name: 'Carrot', type: ['vegetable', 'food'] }
12
]
13
};
14
Where I am stuck, not sure how to now map that type array 😀 Currently just have a.type[0], which is bad.
JavaScript
1
6
1
const groupedData = start.reduce(function (r, a) {
2
r[a.type[0]] = r[a.type[0]] || [];
3
r[a.type[0]].push(a);
4
return r;
5
}, {});
6
Advertisement
Answer
You need to loop over all the elements of a.type
.
JavaScript
1
7
1
const groupedData = start.reduce(function(r, a) {
2
a.type.forEach(type => {
3
r[type] = r[type] || [];
4
r[type].push(a);
5
});
6
return r;
7
}, {});