简体   繁体   English

如何通过在另一个数组中搜索来过滤列表中的数组?

[英]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:假设您的 filterarray 至少被一个(即 OR)使用,您可以像这样:

Use Array#filter to filter for your desire and Array#some for getting all objects with at least one hit.使用Array#filter过滤您的需求,使用Array#some获取至少一次命中的所有对象。
If you want instead all filter than use instead Array#every .如果你想要所有过滤器而不是使用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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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