Skip to content

Instantly share code, notes, and snippets.

@j-quelly
Created January 6, 2019 01:28
Show Gist options
  • Save j-quelly/c23a90c91a6ef2b87c4706708fd95e81 to your computer and use it in GitHub Desktop.
Save j-quelly/c23a90c91a6ef2b87c4706708fd95e81 to your computer and use it in GitHub Desktop.
You have a list of dishes. Each dish is associated with a list of ingredients used to prepare it. You want to group the dishes by ingredients, so that for each ingredient you'll be able to find all the dishes that contain it (if there are at least 2 such dishes). Return an array where each element is a list with the first element equal to the na…
function groupingDishes(dishes) {
const ingredientMap = dishes.reduce((map, dish) => {
dish.slice(1).forEach((ingredient) => {
if (!map[ingredient]) {
map[ingredient] = [dish[0]];
} else {
// if happens more than once it should be an ingredient
map[ingredient].push(dish[0]);
}
});
return map;
}, {});
// console.log(ingredientMap);
const results = [];
Object.keys(ingredientMap).sort().forEach((key) => {
if (ingredientMap[key].length >= 2) {
results.push([key, ...ingredientMap[key].sort()])
}
});
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment