本文正在参与掘金团队号上线活动,点击 查看大厂春招职位
一、题目描述:
求多个数组之间的交集
二、思路分析:
- Array.prototype.reduce(): reduce为数组中的每一个元素依次执行callback函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:
- accumulator 累计器
- currentValue 当前值
- currentIndex 当前索引
- array 数组
回调函数第一次执行时,accumulator 和currentValue的取值有两种情况:如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。
- Array.prototype.filter():
filter()方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
三、AC 代码:
function fn2(...arg) {
return arg.reduce((total, next) => {
console.log(total, next);
return [...total].filter((item) => new Set(next).has(item));
});
}
四、总结:
试着参加掘金活动打个卡;