xszi / javascript-algorithms

算法修炼中...
5 stars 0 forks source link

编写一个函数计算多个数组的交集 #28

Open xszi opened 4 years ago

xszi commented 4 years ago

要求: 输出结果中的每个元素一定是唯一的

xszi commented 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))
    }))]
}