Open xszi opened 4 years ago
方法1:使用reduce + Map
const intersection = (...args) => {
return args.reduce(twoArrayIntersection)
}
const twoArrayIntersection = (arrA, arrB) => {
let map = new Map()
let res = []
arrA.forEach(item => {
map[item] = true
})
arrB.forEach(item => {
if (map[item]) {
res.push(item)
}
})
return res
}
方法2:使用 every
const intersection = (first, ...rest) => {
return [...new Set(first.filter(item => rest.every(arr => arr.includes(item))))]
}
方法3:单使用reduce
const intersection = (...args) => {
// pre 前一个 cur 当前
return [...new Set(args.reduce((pre, cur) => {
return pre.filter(item => cur.includes(item))
}))]
}
要求: 输出结果中的每个元素一定是唯一的