Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Group an array of objects based on multi keys in Javascript?

New member
Joined
Feb 3, 2023
Messages
11
I would like to share with you an existence problem

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;
  }, {});
};
How can I group the data first by city and then by stadium, including any arenas if they exist?
 
New member
Joined
Feb 3, 2023
Messages
17
The required output format is a little strange, but you can indeed do it with a single reduce() statement:

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"
}];

const result = Object.values(
  data.reduce((a, {city, arena, stadium, countries}) => {
    a[city] ??= { city, arena: [], stadium: [] };
    if (arena) a[city].arena.push({ value: arena, countries });
    if (stadium) a[city].stadium.push({ value: stadium, countries });
    return a;
  }, {})
);

console.log(result);
 
Top