Skip to content

Instantly share code, notes, and snippets.

@andersonleite
Created July 15, 2019 20:52
Show Gist options
  • Save andersonleite/a70387bace651b2eb62db8d8431fe55a to your computer and use it in GitHub Desktop.
Save andersonleite/a70387bace651b2eb62db8d8431fe55a to your computer and use it in GitHub Desktop.
Grouping Dishes
// You are given a list dishes, where each element consists of a list of strings beginning with the name of the dish, followed by all the ingredients used in preparing 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 beginning with the ingredient name, followed by the names of all the dishes that contain this ingredient. The dishes inside each list should be sorted lexicographically, and the result array should be sorted lexicographically by the names of the ingredients.
function groupingDishes(dishes) {
let hash = {}
dishes.forEach((dish)=>{
let name = dish[0]
for(let i=1; i<dish.length; i++){
if(!hash[dish[i]]){
hash[dish[i]]=[]
hash[dish[i]].push(name)
}else{
hash[dish[i]].push(name)
}
}
})
return select(hash)
}
function select(hash){
let selected = []
for(const [k,v] of Object.entries(hash)){
if(v.length>1){
let arr = []
arr.push(k)
arr = arr.concat(v.sort())
selected.push(arr)
}
}
return selected.sort((a, b) => a[0] < b[0] ? -1 : a[0] === b[0] ? 0 : 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment