[转]ES6数组:两个数组或数组对象取并集、交集、差集

1取并集

取并集
let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
let arr = Array.from(new Set([...a, ...b]));
console.log('arr',arr);

结果


image.png

2 取交集

let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
let arr = Array.from(new Set([...b].filter(x => a.has(x))));

结果


image.png

3 取差集

let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
let arr = Array.from(new Set([...b].filter(x => !a.has(x))));
console.log('arr',arr);

结果


image.png

数组对象

1取交集

let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];
let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];
let arr = [...b].filter(x => [...a].some(y => y.id === x.id));
console.log('arr',arr)

结果


image.png

2 取差集 (这个比较好用!!!!)

let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];
let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];
let arr = [...b].filter(x => [...a].every(y => y.id !== x.id));
console.log('arr',arr);

结果


image.png
image.png
//保留n位小数并格式化输出(不足的部分补0)
var fomatFloat = function(value, n) {
    var f = Math.round(value*Math.pow(10,n))/Math.pow(10,n);
    var s = f.toString();
    var rs = s.indexOf('.');   
    if (rs < 0) {     
        s += '.';   
    } 
    for(var i = s.length - s.indexOf('.'); i <= n; i++){
      s += "0";
    }
    return s;
}
https://www.cnblogs.com/NazLee/p/11646023.html

https://mp.weixin.qq.com/s?__biz=MzI1NTcxOTQ1Nw==&mid=2247496904&idx=1&sn=f86bf63dee8fc8d0cb7bb864314271df&chksm=ea331586dd449c9048b7dcb70a3c3ac9cf177e534d6ee97fc2454a8e32f1f096530ac69215fe&mpshare=1&scene=23&srcid=0129x84K8C2TwZaWVKjbkA4W&sharer_sharetime=1611892708432&sharer_shareid=c52a8fccb99111557e36e4605bae5135#rd

vue递归组件实现多级列表

https://www.cnblogs.com/fei-H/p/11359028.html

原文地址 https://www.jianshu.com/p/20523688cbee

你可能感兴趣的:([转]ES6数组:两个数组或数组对象取并集、交集、差集)