JavaScript 中数组交集的最简单代码?
假设以下为我们的数组 −
var firstNamesArray=["John","David","Bob","Sam","Carol"]; var secondNamesArray=["Mike","Carol","Adam","David"];
执行数组交集的最简单方法是使用 filter() 以及 includes()。以下是该代码 −
示例
var firstNamesArray=["John","David","Bob","Sam","Carol"]; var secondNamesArray=["Mike","Carol","Adam","David"]; var intersectionOfArray=[]; intersectionOfArray=firstNamesArray.filter(v => secondNamesArray.includes(v)); console.log("Intersection of two array="); console.log(intersectionOfArray);
要运行上面的程序,你需要使用以下命令 −
node fileName.js.
此处,我的文件名是 demo141.js。
输出
这将生成以下输出 −
PS C:\Users\Amit\JavaScript-code> node demo141.js Intersection of two array= [ 'David', 'Carol' ]
广告