0
votes

I was hoping to get some help regarding some filtering in React I'm struggeling with.

I have 2 objects, an object with recipes which I want to filter and an object (filterIds) with all my ID's I want to filter the recipe object with. Each recipe contains a json string (ingredients) which I have to parse first, work in progress... After that I want to check if my recipe at least has the same ingredients as my filtersIds object.

I'm currently using every which returns true if every ingredient is in my filtersIds object. But is also returns false when more ingredients are in my recipe than there are in my filtersIds object. Below is my code:

let filterIds = this.state.selectedIngredients.map(a => parseFloat(a.id));

const filteredArray = this.state.recipes.filter(recipe => {
    let ingredients = JSON.parse(recipe.ingredients).map(a => parseFloat(a.id));
    return (ingredients.every(ingredient => filterIds.indexOf(ingredient) >= 0));
});

The code works, it only returns my recipe when I filter on the exact ingredients of the recipe. What I want is to check if a recipe at least has all the in the filterIds, not the exact same values and amount. Basically my filter function should narrow down the users' search.

1
Please include a sample of the selectedIngredients and recipes collections to help users assist you. - Samuel Goldenbaum

1 Answers

1
votes

You are currently checking if all the elements of ingredients array are included in the filterIds array. But what you need is to check if all the elements of filterIds array are included in the ingredients array.

return (filterIds.every(filterId => ingredients.indexOf(filterId) >= 0));