前端笔试题(3)-使用Set去重合并
1.去重
arr1=[1,1,2,2,3,3,3,4]
arr2=[...new Set(arr1)]//[1,2,3,4]
2.去重加合并
(1)复杂
function union(arr1:any, arr2:any) {
const setA = new Set(arr1)
const setB = new Set(arr2)
let _union = new Set(setA)
for (let elem of setB) {
_union.add(elem);
}
return [..._union];
}
union([1, 2, 3], [2, 3, 4])//[1,2,3,4]
(2)更简单的(先合并再去重)
function union(arr1:any,arr2:any) {
const setA = new Set([...arr1, ...arr2])
return [...setA]
}
本文来自博客园,🐱🚀作者:FAIGEL,打字创作不易,如转载请注明原文链接:https://www.cnblogs.com/FAIGEL/articles/17286335.html。谢谢✨

浙公网安备 33010602011771号