Reputation: 1277
i have a short question:
I want to filter an array of objects by two arrays of strings.
My Array looks like this:
[
{
"id": 12345,
"title": "Some title",
"contains": [
{
"slug": "fish",
"name": "Fish"
}, {
"slug": "soy", // search term, like a id
"name": "Soy"
}
], "complexity": [
{
"slug": 4, // search term, like a id
"name": "hard"
}, {
}],..
},
{...}
and that are my two arrays:
// recipes should not contain this ingredients
let excludedIngredientsArray = Array<string> = ["soy", "fish"];
// recipes should not contain this complexities
let excludedComplexityArray = Array<string> = [1, 2];
Now i want to filter the recipes by these two arrays and want to remove all recipes which contain the excluded terms
Whats the best way to do this?
Thanks a lot!
edit:
recipeArray looks like this:
interface recipeArray {
reciepe: Array<{
name: string,
contains: Array<{slug: string, name: string}> //Ingredients array
complexity: Array<{slug: string, name: string}> //complexity array
}>
}
Upvotes: 0
Views: 165
Reputation: 164139
If your first array is like this:
interface Item {
id: number;
title: string;
contains: { slug: string; name: string }[],
complexity: { slug: number; name: string }
}
let data: Item[];
Then you can have your desired filtered array like so:
let excluded = data.filter(item => {
return item.contains.every(obj => excludedIngredientsArray.indexOf(obj.slug) < 0)
&& excludedComplexityArray.indexOf(item.complexity.slug) < 0;
});
Upvotes: 2