New member
- Joined
- Feb 3, 2023
- Messages
- 11
- Thread Author
- #1
I would like to share with you an existence problem
I have array as follows
I want to group it first by city then by stadium and arena if exist How can I achieve this
output like :
I was able to group by city with reduce
How can I group the data first by city and then by stadium, including any arenas if they exist?
I have array as follows
Code:
const data = [
{
"countries": ["France", "USA", "Canada"],
"city": "Paris",
"stadium": "Parce de france"
},
{
"countries": ["France", "Itlay", "Spain"],
"city": "Roma",
"arena": "La cigal"
},
{
"countries": ["France"],
"city": "Roma",
"stadium": "Olymico"
},
{
"countries": ["France"],
"city": "Paris",
"arena": "Velodrome"
},
]
I want to group it first by city then by stadium and arena if exist How can I achieve this
output like :
Code:
{
"city": "Paris",
"arena": [
{
"value":"Velodrome",
"countries": ["France"]
}
],
"stadium": [
{
"value":"Parce de france",
"countries": ["France", "USA", "Canada"]}
]
}
{
"city": "Roma",
"arena": [
{
"value":"La cigal",
"countries": ["France", "Itlay", "Spain"]
}
],
"stadium": [
{
"value":"Olymico",
"countries": ["France"]
}
]
}
]
I was able to group by city with reduce
Code:
let group = function(array, key) {
return array.reduce(function(result, item) {
(result[item[key]] = result[item[key]] || []).push(item);
return result;
}, {});
};