Skip to content Skip to sidebar Skip to footer

Filter Objects Against Multiple Values, Only Returning Perfect Matches

I have a set of recipe objects, each including an ingredients key with an array of values - like this: 'soup': {'ingredients': ['carrot', 'pepper', 'tomato']}, 'pie': {'ingredient

Solution 1:

  1. Extract the key-value pairs from your object with Object.entries
  2. Filter out any that don't have all of their ingredients in the shoppingList with Array#every and Array#includes.
  3. Use Array.map to get just the keys.

var recipes = {
  'soup': {'ingredients': ['carrot', 'pepper', 'tomato']}, 
  'pie': {'ingredients': ['carrot', 'steak', 'potato']}, 
  'stew': {'ingredients': ['steak', 'pepper', 'tomato']}
};

var shoppingList = ['carrot', 'steak', 'tomato', 'pepper']

var result = Object.entries(recipes)//1. get the key-value pairs
  .filter(([key, {ingredients}]) => ingredients.every(t => shoppingList.includes(t))) //2. filter them
  .map(([key]) => key) //3. get the keys onlyconsole.log(result);

Solution 2:

Use .every() with .includes() inside the .filter() callback.

return query.every(q => obj.taggedItems.includes(q))

Post a Comment for "Filter Objects Against Multiple Values, Only Returning Perfect Matches"