To start, organize your data into an array of objects. Then, employ the subsequent algorithm to extract the desired information:
- Determine the unique categories
["Music", "Film", "History", "Science"]
- Generate combinations from those categories
[["Music", "Film"], ["Music", "History"], ["Music", "Science"], ["Film", "History"], ...]
- Establish a mapping of category names to the books they contain using a
Set
for uniqueness. The map will follow this structure: "{"Music": Set("A", "B"), "Film": Set("A", "B", "C"), "History": Set("C", "B"), "Science": Set("C")}
"
- Utilize the previously created objects and arrays to identify duplicates within the combinations.
- After completion, you'll have an array structured as follows:
[ [cat1, cat2, [bookInCommon1, bookInCommon2]], [cat1, cat3, [bookInCommon1, bookInCommon2]], ...]
Execute the code below to witness it in action. mongoData
stores the data fetched from MongoDB.
const mongoData = [{
category: "Music",
book: "A"
}, {
category: "Music",
book: "B"
},{
...
}];
// Steps outlined above
...
combos.forEach(combo => {
console.log("Combo: " + combo[0] + ", " + combo[1]);
console.log("\tNumber of dupes: " + combo[2].length);
});