Skip to content
Advertisement

Matching 2 arrays based on the values of some fields

I have the following list of ingredients in an array called myBar. The ingredient is contained in the attribute “name”

JavaScript

I also have a second array called cocktailList containing a list of cocktail recipes. In here the ingredients are contained within the field “ingredients”.

JavaScript

I’m trying to check what cocktails I can make based on a match of the content of the ingredients. The idea is to iterate each recipe (in cocktailList) and check that ALL ingredients are also part of my list of ingredients in myBar.

For example “drinkId”: “1102” should return true since I have all ingredients (vodka and orange juice) in myBar while “drinkId”: “1101” should return false since I don’t have neither lime syrup nor lime.

Advertisement

Answer

Create an array of ingredients names from first array, so that you can quickly search for an ingredient in direct array.

JavaScript

Now loop through cocktailList and for each ingredient search in arrName. If count of matching element is equal to count of ingredients in cocktail then its a match.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement