I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example:
4 Categories with Subjects
['A','B','D']
['C']
['E','F']
['G','H','I','J']
In addition to the categories, I have another set of arrays where each item can have up to four possible subjects:
3 Items with Subjects
['A','F']
['E','I','C']
['E','F','G']
My goal is to accurately count the number of items in each category. The expected results are:
Total Items: 3
Category 1: 1
Category 2: 1
Category 3: 3
Category 4: 2
However, there is an issue when items belong to multiple categories. In this case, my results become:
Total Items: 3
Category 1: 1
Category 2: 1
Category 3: 4
Category 4: 2
The discrepancy occurs because one of the items has two subjects within the same category, E and F.
Approaches Attempted
To provide some context, the categories are stored as objects in an array:
categories = [
{ name: string, subjects: string[], count: number }
]
The items follow a similar pattern:
items = [
{ subjects: Subject[] }
]
Where Subject is defined as:
{ id: string, name: string }
The issue lies in the following segment of code:
categories.map(category =>
category.subjects.map(categorySubject => {
if(items.subjects.map(itemSubject => itemSubject.id)
.some(val => itemSubject.indexOf(val) === 0)) {
category.count++;
}
}));
Although I initially used 'some' to approach the problem, I need to find a way to prevent double-counting for items with multiple subjects in one category. It's clear that my current method is the root cause of the error. While tweaking how the categories are organized could be an option, adjusting the items structure might also provide a solution.