关于js2个数组取差集怎么取
例如求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 duce(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);indexof的用法javascript
12 } else {
13 tmp.splice(tmp.indexOf(val1), 1);
14 }
15 });
16
17 console.at(tmp));
18 }
19
20 // 输出 [ 1, 9, 0, 7, 8 ]
21 difference(arr1, arr2);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论