0

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
    }>
}
2
  • What is the type definition for the first array? Commented Jan 26, 2017 at 14:41
  • At the moments its <any>, but i will add this later. Commented Jan 26, 2017 at 14:43

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Oh nice, that was easy! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.