I have an array of objects (addresses) and I want to /group this array based on the city property and return a new array of arrays. Of course, I don't know how many different cities are in the input array. I took a look at similar questions but couldn't figure out how to do that. I just need a general and dynamic logic. Also, if possible, I want to first see the old vanilla JavaScript solution.
Input
const props = [
{
description: 'berlin1',
address: {
street: 'address here',
city: 'berlin'
}
},
{
description: 'munich1',
address: {
street: 'address here',
city: 'munich'
}
},
{
description: 'berlin2',
address: {
street: 'address here',
city: 'berlin'
}
},
{
description: 'munich2',
address: {
street: 'address here',
city: 'munich'
}
},
{
description: 'berlin3',
address: {
street: 'address here',
city: 'berlin'
}
},
{
description: 'hamburg1',
address: {
street: 'address here',
city: 'hamburg'
}
},
{
description: 'berlin4',
address: {
street: 'address here',
city: 'berlin'
}
}
]
Output:
const output = [
[
{
description: 'berlin1',
address: {
street: 'address here',
city: 'berlin'
}
},
{
description: 'berlin2',
address: {
street: 'address here',
city: 'berlin'
}
},
{
description: 'berlin3',
address: {
street: 'address here',
city: 'berlin'
}
},
{
description: 'berlin4',
address: {
street: 'address here',
city: 'berlin'
}
}
],
[
{
description: 'munich1',
address: {
street: 'address here',
city: 'munich'
}
},
{
description: 'munich2',
address: {
street: 'address here',
city: 'munich'
}
}
],
[
{
description: 'hamburg1',
address: {
street: 'address here',
city: 'hamburg'
}
}
]
]