You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript统计两个数组中的公共元素数量

JavaScript统计两个数组公共元素数量的方法

方法一:利用Set优化查找(高效方案)

将其中一个数组转换为Set(查找时间复杂度O(1)),遍历另一个数组统计存在于Set中的元素数量,适合处理较大规模的数组:

const obj1 = [
 'Anime',
 'Movies/TV Series',
 'Coding',
 'Cooking',
 'Sport/Fitness',
 'Gaming'
];
const obj2 = [
 'Music',
 'Movies/TV Series',
 'Coding',
 'Party/Night Clubs',
 'Gaming',
 'Traveling',
 'Roleplay'
];

// 优先转换较短的数组为Set,进一步提升性能
const elementSet = new Set(obj1);
let commonCount = 0;

for (const item of obj2) {
  if (elementSet.has(item)) {
    commonCount++;
  }
}

console.log(commonCount); // 输出:3

方法二:使用数组filter+includes(直观写法)

通过filter筛选出obj1中同时存在于obj2的元素,再取结果数组的长度,写法简洁但效率略低(时间复杂度O(n*m)):

const obj1 = [
 'Anime',
 'Movies/TV Series',
 'Coding',
 'Cooking',
 'Sport/Fitness',
 'Gaming'
];
const obj2 = [
 'Music',
 'Movies/TV Series',
 'Coding',
 'Party/Night Clubs',
 'Gaming',
 'Traveling',
 'Roleplay'
];

const commonElements = obj1.filter(item => obj2.includes(item));
const commonCount = commonElements.length;

console.log(commonCount); // 输出:3

两种方法最终都能得到两个数组的公共元素数量(示例中为3,对应'Movies/TV Series'、'Coding'、'Gaming')。

内容的提问来源于stack exchange,提问作者Anis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 08:40:30