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

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]

posted @ 2022-05-11 09:12  下一秒钟已经不同  阅读(23)  评论(0编辑  收藏  举报