美文网首页Web前端之路前端干货
es6数组取交集/并集/合集/去重

es6数组取交集/并集/合集/去重

作者: Cherry9507 | 来源:发表于2020-03-30 20:39 被阅读0次
    
    var a = [1,2,3,4,5]
    var b = [2,4,6,8,10]
    console.log("数组a:", a);
    console.log("数组b:", b);
     
    var sa = new Set(a);
    var sb = new Set(b);
     
    // 交集
    let intersect = a.filter(x => sb.has(x));
     
    // 差集
    let minus = a.filter(x => !sb.has(x));
     
    // 补集
    let complement  = [...a.filter(x => !sb.has(x)), ...b.filter(x => !sa.has(x))];
     
    // 并集
    let unionSet = Array.from(new Set([...a, ...b]));
     
    console.log("a与b的交集:", intersect);
    console.log("a与b的差集:", minus);
    console.log("a与b的补集:", complement);
    console.log("a与b的并集:", unionSet);
    //去重 2种方法
    const arr = [1,1,1,23,4,5,6]
    let newArr = Array.from(new Set(arr))
    let newArr1 = [...new Set(arr)]
    console.log(newArr,newArr1)
    

    相关文章

      网友评论

        本文标题:es6数组取交集/并集/合集/去重

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