I had an object with this structure:
[
{
"event_id": 1,
"subjects": [
{
"id": 12,
"name": "Chemistry"
},
{
"id": 13,
"name": "Physics"
},
{
"id": 14,
"name": "Psychology"
},
{
"id": 16,
"name": "History"
}
]
},
{
"event_id": 2,
"subjects": [
{
"id": 11,
"name": "Maths"
},
{
"id": 12,
"name": "Chemistry"
},
{
"id": 14,
"name": "Biology"
},
{
"id": 15,
"name": "Geography"
}
]
},
{
"event_id": 3,
"subjects": [
{
"id": 14,
"name": "Biology"
},
{
"id": 15,
"name": "Geography"
},
{
"id": 16,
"name": "History"
}
]
}
]
What will be the fastest way to get all possible values of subjects prop in this option? Is this only possible to achieve by looping through each single sub-object and push value to "counting array" if it not already there?
3
Answers
The simplest and most readable way would indeed be to loop through the subjects and add them to the array if they don’t exist.
Another useful way is to use a Set with spread syntax to deduplicate the values in the array.
just because there’s several ways to do the same things, here’s one with
reduce