array/intersectArr.jsjavascript
/**
* 返回两个数组之间的交集
* @function intersectArr
* @memberof module:array
* @param {Array} a 基准数组
* @param {Array} b 用于比较的数组
* @returns {Array} 去重后的交集数组
* @throws {TypeError} 参数不是数组时抛出
*/
function intersectArr(a, b) {
if (!Array.isArray(a) || !Array.isArray(b)) {
throw new TypeError('a and b must be arrays')
}
const setB = new Set(b)
return uniqueValues(a.filter(item => setB.has(item)))
}
/**
* 对数组值去重。
* @private
*/
function uniqueValues(values) {
return [...new Set(values)]
}
export default intersectArr