关于 js 2个数组取差集怎么取

https://www.cnblogs.com/jiechen/p/5694966.html

 

 

例如求var arr1 = [1]; var arr2 = [1,2];的差集
方法一:

1 Array.prototype.diff = function(a) {
2     return this.filter(function(i) {return a.indexOf(i) < 0;});
3 };
4 [1,2].diff([1]);//[2]  

方法二:

 1 var isNaN = Number.isNaN;
 2 var difference = function(arr1, arr2) {
 3     return arr1.reduce(function(previous, i) {
 4         var found = arr2.findIndex(function(j) {
 5             return j === i || (isNaN(i) && isNaN(j));
 6         });
 7         return (found < 0 && previous.push(i), previous);
 8     }, []);
 9 };
10 
11 
12 var arr1 = [1];
13 var arr2 = [1, 2];
14 
15 console.log(difference(arr2, arr1)); //[ 2 ]

方法三:

 1 // ES6 的 Set 来处理,这是真正按照数学上的集合来进行的,不会有重复元素
 2 var subSet = function(arr1, arr2) {
 3     var set1 = new Set(arr1);
 4     var set2 = new Set(arr2);
 5 
 6     var subset = [];
 7 
 8     for (let item of set1) {
 9         if (!set2.has(item)) {
10             subset.push(item);
11         }
12     }
13 
14     return subset;
15 };
16 //普通方法
17 var subSet = function(arr1, arr2) {
18     var len = arr1.length;
19     var arr = [];
20 
21     while (len--) {
22         if (arr2.indexOf(arr1[len]) < 0) {
23             arr.push(arr1[len]);
24         }
25     }
26 
27     return arr;
28 };

 方法四:

 1 // 数组求差值
 2 var arr1 = [1, 2, 4, 9, 0];
 3 var arr2 = [2, 4, 7, 8];
 4 
 5 var difference = function(arr1, arr2) {
 6   var diff = [];
 7   var tmp = arr2;
 8 
 9   arr1.forEach(function(val1, i){
10     if (arr2.indexOf(val1) < 0) {
11       diff.push(val1);
12     } else {
13       tmp.splice(tmp.indexOf(val1), 1);
14     }
15   });
16 
17   console.log(diff.concat(tmp));
18 }
19 
20 // 输出 [ 1, 9, 0, 7, 8 ]
21 difference(arr1, arr2);
posted @ 2019-09-26 14:22  小小公举  阅读(14054)  评论(0编辑  收藏  举报