美文网首页
set 实践

set 实践

作者: 路尔轩 | 来源:发表于2021-12-20 15:26 被阅读0次
let arr = [1,2,3,4,5,4,3,2,1];
// 1.数组去重
let result = [...new Set(arr)];
console.log('数组去重', result)
// 2.交集
let arr2 = [4,5,6,5,6]
let result2 = [...new Set(arr)].filter(item => {
    let s2 = new Set(arr2);
    if(s2.has(item)){
        return true
    }else{
        return false
    }
})
console.log('交集', result2)
// 简写
let reault3 = [...new Set(arr)].filter(item => new Set(arr2).has(item))
console.log('简写交集', reault3)
// 3.并集
let union = [...new Set([...arr, ...arr2])]
console.log('并集', union)
// 4.差集
let diff = [...new Set(arr)].filter(item => !(new Set(arr2).has(item)))
console.log('差集', diff)

相关文章

网友评论

      本文标题:set 实践

      本文链接:https://www.haomeiwen.com/subject/relzfrtx.html