Having the following array of objects of ingredients used by cooks
images = [{id:1, cook:"jim", ingredients:"chicken salsa mayo ketchup tomato"},
{id:2, cook:"steve", ingredients:"pasta mozzarela chicken"},
{id:3, cook:"jim", ingredients:"bread lettuce tomato onions"},
{id:4, cook:"jim", ingredients:"ketchup sausage bread"},
{id:5, cook:"jim", ingredients:"avocado ground_meat chili"},
{id:6, cook:"jim", ingredients:"ground_meat guacamole tomato parsley"},
{id:7, cook:"steve", ingredients:"chicken tomato broccoli"}]
I have to extract an array of ingredients used by a specific cook so that each ingredient appears only once, return only 25 ingredients unless a specific limit is provided.
extractIngredients(array, cook, limit=25)
e.g:
extractIngredients(images, "jim", 10) ==> ["chicken", "salsa", "mayo", "ketchup", "tomato", "bread", "lettuce", "onions", "hotdog", "avocado"]
BONUS POINTS:
Return an ingredient array sorted by the number of occurrences, and then alphabetically, showing the most popular ingredients first.
e.g:
extractIngredients(images, "jim", 10) ==> ["tomato", "bread", "ground_meat", "ketchup", "avocado", "chicken", "chili", "guacamole", "lettuce", "mayo"]
My solution:
extractIngredients(images, username, limit){
return [...new Set(images.filter(images => images.cook == username)
.map(a => a.keywords.split(" ")).flat())].slice(0, limit);
}
My solution has an issue with an extremely large input as it would still process all of the objects and then slice the resulting array. It would be better to just process objects until the limit is reached.