Can we achieve a group by on an array of objects by object's key where key is also an array?
[
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
]
Wanted results in an object after the group by:
{
"fruits": [
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
],
"vegetables": [
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
]
}
Vanilla or Lodash solution is very welcome!
Edit
Thanks everyone, here is what I ended up using:
const groupBy = key => array =>
array.reduce((obj, el) => {
el[key].forEach(k => {
obj[k] = obj[k] || []
obj[k].push({ ...el })
})
return obj
}, {})
const groupBySomething = groupBy(`something`)
const grouped = groupBySomething(data)