一天一个仿lodash函数实现-intersection
作者:互联网
intersection
这个和前面写的difference反过来,difference是求未出现过的,intersection是求出现过的,所以实现起来就比较简单了。
function intersection(arr, ...rest){
const left = rest.reduce((pre, cur)=>{
return pre.concat(cur.map(item=>iteratee(item)))
}, []);
return arr.filter(item=>left.includes(item))
}
function intersectionBy(arr, ...rest){
const iterateeKey = rest[rest.length-1]
const iteratee = typeof iterateeKey === 'string'?(item)=>item[iterateeKey]:iterateeKey;
const left = rest.slice(0, rest.length-1).reduce((pre, cur)=>{
return pre.concat(cur.map(item=>iteratee(item)))
}, []);
return arr.filter(item => {
return left.includes(iteratee(item))
})
}
function intersectionWith(arr, ...rest){
const comparator = rest[rest.length - 1]
const left = rest.slice(0, rest.length-1).reduce((pre, cur)=>{
return pre.concat(cur)
}, []);
return arr.filter(item => {
for(let i=0;i<left.length;i++) {
if(comparator(left[i], item)) {
return true;
}
}
return false
})
}
标签:pre,arr,return,lodash,rest,item,const,intersection,函数 来源: https://www.cnblogs.com/dont27/p/16372894.html