如何根据另一个数组过滤一个数组?

时间:2021-03-19 18:47:07

标签: javascript reactjs

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

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

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

我基本上是想根据 apps 中的元素过滤 securityApps

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

这是我的开始:

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

apps 后来实现为

apps.map(...

2 个答案:

答案 0 :(得分:3)

您可以这样做,使用 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 postindexOf 在 chrome 上可能更快。

答案 1 :(得分:2)

非常简单的答案

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