其他分享
首页 > 其他分享> > 定义函数计算两个数组的交集

定义函数计算两个数组的交集

作者:互联网

function fn(a, b) {
const result = [];
const map = a.reduce((obj, item) => {
obj[item] ? obj[item]++ : obj[item] = 1;
return obj;
}, {});
b.forEach(item => {
if (map[item] && map[item] > 0) {
result.push(item);
map[item]--
}
})
return result
}
console.log(fn([1, 2, 1], [2, 2, 1])) // [2, 1]

标签:map,obj,定义,交集,item,result,数组,return,const
来源: https://www.cnblogs.com/sj-blogs/p/16256584.html