2019-05-09
描述
返回两个数组中都存在的元素列表。
提示
- 从数组
b中创建一个Set - 使用
Set.prototype.has()判断是否存在相同的值 - 对数组
a使用Array.prototype.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]
ME!
链滴