const mongoData = [{
category: "Music",
book: "A"
}, {
category: "Music",
book: "B"
},{
category: "Music",
book: "A"
},{
category: "Film",
book: "A"
},{
category: "Film",
book: "A"
},{
category: "Film",
book: "B"
},{
category: "Film",
book: "C"
},{
category: "Film",
book: "C"
},{
category: "Film",
book: "A"
},{
category: "History",
book: "C"
},{
category: "History",
book: "C"
},{
category: "History",
book: "B"
},{
category: "History",
book: "B"
},{
category: "Science",
book: "C"
},{
category: "Science",
book: "C"
},{
category: "Science",
book: "C"
}];
// Step 1: Get the categories
const categories = Array.from(new Set(mongoData.map(x => x.category)));
// Step 2: Get combinations of those categories
const combos = [];
for(let i = 0; i < categories.length - 1; i++) {
let outerCat = categories[i];
for(let j = i + 1; j < categories.length; j++) {
let innerCat = categories[j];
combos.push([
outerCat,
innerCat
]);
}
}
// Step 3: Map the categories to the books that they contain
const catBooks = mongoData.reduce((map, entry) => {
map[entry.category] = map[entry.category] || new Set();
map[entry.category] = map[entry.category].add(entry.book);
return map;
}, {});
// Step 4: Get the duplicate books for each combo
combos.forEach((combo, index) => {
const cat1 = combo[0];
const cat2 = combo[1];
const cat1BooksArr = Array.from(catBooks[cat1]);
const cat2BooksSet = catBooks[cat2];
const dupes = cat1BooksArr.filter(book => {
return cat2BooksSet.has(book);
});
combos[index].push(dupes); // push into combos array
});
// Done! Your combos array contains arrays that look like this: [cat1, cat2, [dupes]]
combos.forEach(combo => {
console.log("Combo: " + combo[0] + ", " + combo[1]);
console.log("\tNumber of dupes: " + combo[2].length);
});