JavaScript:提取两个数组相同值至第三个数组的实现方法
解决数组交集问题:找出两个数组的相同值存入第三个数组
嘿,这个需求太常见啦!不管是处理店铺列表还是其他数据交集场景,都有好几种靠谱的实现方式,我给你整理了几个不同场景下的方案,都能得到你想要的MatchedArray结果~
方法1:基础双重循环(适合理解底层逻辑)
这种方法最直观,适合刚入门的同学搞清楚底层比对逻辑,一步一步来不绕弯:
const Array1 = ["Store1", "Store2", "Store3", "Store4"]; const Array2 = ["Store6", "Store1", "Store3", "Store999"]; const MatchedArray = []; // 遍历静态数组的每一项 for (let i = 0; i < Array1.length; i++) { // 遍历动态数组的每一项,找匹配 for (let j = 0; j < Array2.length; j++) { if (Array1[i] === Array2[j]) { MatchedArray.push(Array1[i]); // 找到匹配项就跳出内层循环,避免没必要的遍历 break; } } } console.log(MatchedArray); // 输出:["Store1", "Store3"]
方法2:数组内置方法(简洁优雅,日常开发首选)
用JS数组的filter和includes方法,一行核心代码就能搞定,非常清爽:
const Array1 = ["Store1", "Store2", "Store3", "Store4"]; const Array2 = ["Store6", "Store1", "Store3", "Store999"]; // 过滤出Array1中同时存在于Array2的元素 const MatchedArray = Array1.filter(item => Array2.includes(item)); console.log(MatchedArray); // 输出:["Store1", "Store3"]
解释:filter会遍历Array1的每个元素,includes负责检查当前元素是否存在于Array2中,返回true的元素会被自动收集到新数组里,完全符合你的需求。
方法3:用Set优化性能(大数据量场景必备)
如果你的数组数据量很大(比如上千上万条),上面两种方法的查找效率会有点低。这时候用Set来优化,把查找时间从O(n)降到O(1),性能提升明显:
const Array1 = ["Store1", "Store2", "Store3", "Store4"]; const Array2 = ["Store6", "Store1", "Store3", "Store999"]; // 把动态数组转成Set,因为Set的has方法查找速度远快于数组的includes const array2Set = new Set(Array2); // 过滤出Array1中存在于Set的元素 const MatchedArray = Array1.filter(item => array2Set.has(item)); console.log(MatchedArray); // 输出:["Store1", "Store3"]
额外小提示
如果你的数组里存在重复元素(比如Array1里有两个Store1),上面的方法会把重复的匹配项也存入MatchedArray。如果需要去重的结果,可以在最后加一步:
const uniqueMatchedArray = [...new Set(MatchedArray)];
内容的提问来源于stack exchange,提问作者Elvira
相关产品推荐
相关产品推荐

