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

时间:2020-08-28 19:20:26

标签: javascript arrays angular typescript

我想在一个列表中进行过滤,然后在另一个列表中进行搜索

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

像这样...

    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

4 个答案:

答案 0 :(得分:1)

假设您的filterarray至少被一个(即OR)使用,则可以这样:

使用Array#filter过滤您的需求,使用Array#some过滤所有具有至少一击的物体。
如果要代替使用所有过滤器,请改为使用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);

答案 1 :(得分:0)

您可以像这样过滤数组:

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

答案 2 :(得分:0)

我认为问题存在一些问题,但是如果我理解该问题而忽略了错误的部分,那么遵循以下代码段就可以了。

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']))

答案 3 :(得分:0)

非常感谢您提供的所有提示和支持,基于我通过以下代码成功解决的示例:

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