【问题标题】:Filter complex array by another array用另一个数组过滤复数数组
【发布时间】:2021-07-02 11:38:43
【问题描述】:
let array1 = [
                {
                    id: 1,
                    genres: [
                        { id: 4, title: "qqqq" },
                        { id: 9, title: "zzzz" },
                        { id: 8, title: "eeee" },
                    ],
                },
                {
                    id: 2,
                    genres: [
                        { id: 2, title: "qwert" },
                        { id: 4, title: "asdf" },
                        { id: 5, title: "zxxcc" },
                    ],
                },
            ];

let array2 = [6, 8];

如果 array2 中存在流派 id,我需要过滤 array1。 所以在输出中我应该只有 array1 的第一个元素。

怎么做?

【问题讨论】:

    标签: javascript arrays filter


    【解决方案1】:

    您可以使用filtersomeincludes 的组合:

    let array1 = [{id:1,genres:[{id:4,title:"qqqq" },{id:9,title:"zzzz"},{id:8,title:"eeee" }]},
                  {id:2,genres:[{id:2,title:"qwert"},{id:4,title:"asdf"},{id:5,title:"zxxcc"}]}];
    let array2 = [6, 8];
    
    let result = array1.filter(({genres}) => genres.some(({id}) => array2.includes(id)));
    console.log(result);

    【讨论】:

      【解决方案2】:

      使用filter 函数。

      一种方法:

      let result = array1.filter(el => {
      
          let output = false;
          el.genres.forEach( genre => {
              if (array2.includes(genre.id))
                  output = true;
          });
      
          return output;
      });
      

      【讨论】:

      • 如果它已经匹配了一个值,你也可以在 foreach 循环中添加一个中断来停止它。
      猜你喜欢
      • 1970-01-01
      • 2022-01-16
      • 2017-05-08
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多