简体   繁体   中英

how can I filter an array within a list by searching in another array?

I would like some idea to make a filter in one list searching in another list

how can I filter an array within a list by searching in another array?

like this...

    myArray = [
      {
        "name": "Item-A", "tags":
          ["Facebook", "Google"]
      },
      {
        "name": "Item-B", "tags":
          ["Facebook", "Google", "Apple"]
      },
      {
        "name": "Item-C", "tags":
          ["Apple"]
      },
    ];

    //array for filter
    paramsFilter = ["Facebook", "Apple"];

    //result espected
    [
      {
        "name": "Item-B", "tags":
          ["Facebook", "Google", "Apple"]
      },
      {
        "name": "Item-C", "tags":
          ["Apple"]
      },
    ]```


I am doing a filter by tags so that it will check "paramsFilter" and filter the result that corresponds to all selected tags
for example: 
   if "paramsFilter" = ["Apple", "Microsoft"] the result expected is = [] for not matching all selected tags

Thank you all

Assuming that your filterarray is used by at least one (ie OR) you could make it like this:

Use Array#filter to filter for your desire and Array#some for getting all objects with at least one hit.
If you want instead all filter than use instead Array#every .

 myArray = [ { "name": "Item-A", "tags": ["Facebook", "Google"] }, { "name": "Item-B", "tags": ["Facebook", "Google", "Apple"] }, { "name": "Item-C", "tags": ["Apple"] }, { "name": "Item-D", "tags": ["Dell"] }, ]; paramsFilter = ["Facebook", "Apple"]; let res = myArray.filter(({tags}) => tags.some(tag => paramsFilter.includes(tag))); console.log(res);

您可以像这样过滤数组:

    myArray.filter((value) => value.tags.join("")!== paramsFilter.join(""))

I think question has some issue, but if i understand the question ignoring the part where it is wrong, following snippet should work.

 const myArray = [ { "name": "Item-A", "tags": ["Facebook", "Google"] }, { "name": "Item-B", "tags": ["Facebook", "Google", "Apple"] }, { "name": "Item-C", "tags": ["Apple"] }, ]; function filterArray(params) { return myArray.filter(i => i.tags.filter((n) => params.indexOf(n) > -1).length > 0); } console.log(filterArray(['Apple']))

非常感谢您提供的所有提示和支持,基于我使用以下代码设法解决的示例:

myArray.filter(item => paramsFilter.every(tag => item.tags.some(option => option === tag)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM