Given an array of objects with some common properties like foosWithBar
, how can I create another array of objects grouped by those common properties like barsWithFoos
without using libraries like lodash? I've found examples that create an object grouped by key using reduce()
, but that is not quite what I want.
const foosWithBar = [
{
id: 'Foo A',
bar: {
id: 'Bar 1',
},
},
{
id: 'Foo B',
bar: {
id: 'Bar 1',
},
},
{
id: 'Foo C',
bar: {
id: 'Bar 2',
},
},
{
id: 'Foo D',
bar: {
id: 'Bar 2',
},
},
]
const barsWithFoos = [
{
id: 'Bar 1',
foos: [
{
id: 'Foo A',
},
{
id: 'Foo B',
},
],
},
{
id: 'Bar 2',
foos: [
{
id: 'Foo C',
},
{
id: 'Foo D',
},
],
},
]