intersection - 数组交集

优质
小牛编辑
117浏览
2023-12-01

返回两个数组中都存在的元素列表。

根据数组 b 创建一个 Set 对象,然后在数组 a 上使用 Array.filter() 方法,只保留数组 b 中也包含的值。

const intersection = (a, b) => {
  const s = new Set(b);
  return a.filter(x => s.has(x));
};
intersection([1, 2, 3], [4, 3, 2]); // [2,3]