【问题标题】:How to filter an array based on another array?如何根据另一个数组过滤一个数组?
【发布时间】:2021-03-19 18:47:07
【问题描述】:

我一直在为这个简单的改变而苦苦挣扎。我基本上有两个数组:

let apps = [{name: "Insights", id: "INS"}, {name: "Recruit", id: "REC"}];

let securityApps = ["bw", "INS"];

我基本上是在尝试根据securityApps 中的元素过滤掉apps

我想要达到的结果是: [{name: "Insights", id: "INS"}];(因为 INS 是他们在 ID 方面的共同点)但仍然传入 apps 变量

这是我开始的:

apps.filter((app) => {
        securityApps.forEach((sgApp) => {
          if (app.id === sgApp){
            return app;
          }
        })
      });

apps 后来实现为

apps.map(...

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你可以这样做,使用filterindexOfincludes

    let apps = [{
      name: "Insights",
      id: "INS"
    }, {
      name: "Recruit",
      id: "REC"
    }];
    
    let securityApps = ["bw", "INS"];
    
    const filtered = apps.filter(app => securityApps.indexOf(app.id) > -1)
    
    console.log(filtered)
    
    const filtered2 = apps.filter(app => securityApps.includes(app.id))
    
    console.log(filtered2)

    使用indexOf 会更好,因为includes 在没有polyfill 的Internet Explorer 中不起作用。根据this post,也许indexOf 在chrome 上更快。

    【讨论】:

    • 感谢@Ajeet 分享兼容性问题
    • 没问题
    • @ZiaurRehman 我认为使用includes 更简洁、更短。和 Internet Explorer usage share is extremely low。哪个更快将不断变化,没有人关心。正如您的answer 所建议的那样,includes 简短而干净。 +1
    • 谢谢@AjeetShah!
    【解决方案2】:

    很简单的答案

    const newArray = apps.filter(app => securityApps.includes(app.id)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-30
      • 2014-05-03
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      相关资源
      最近更新 更多