Hello developers, I have a question about how to categorize an array of objects with different values into specific sub-groups based on certain criteria. Each subgroup should contain objects with specific values according to the queried key.
Here is an example array:
const cars =
[ { make: 'audi', model: 'r8', year: '2012' }
, { make: 'audi', model: 'rs5', year: '2013' }
, { make: 'ford', model: 'mustang', year: '2012' }
, { make: 'ford', model: 'fusion', year: '2015' }
, { make: 'kia', model: 'optima', year: '2012' }
]
I want to group by the key make
and create a subgroup called 2nd_class
for objects where the value in the make
key is either kia
or ford
. The rest should be grouped under 1rst_class
.
The expected result would look like this:
const expected =
[ '2nd_class':
[ { make: 'ford', model: 'mustang', year: '2012' }
, { make: 'ford', model: 'fusion', year: '2015' }
, { make: 'kia', model: 'optima', year: '2012' }
]
, '1rst_class' :
[ { make: 'audi', model: 'r8', year: '2012' }
, { make: 'audi', model: 'rs5', year: '2013' }
]
]
I haven't been able to find examples online that address grouping by key and multiple values. Any help would be greatly appreciated!