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

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

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

方法二:

 var isNaN = Number.isNaN;
var difference = function(arr1, arr2) {
return arr1.reduce(function(previous, i) {
var found = arr2.findIndex(function(j) {
return j === i || (isNaN(i) && isNaN(j));
});
return (found < 0 && previous.push(i), previous);
}, []);
}; var arr1 = [1];
var arr2 = [1, 2]; console.log(difference(arr2, arr1)); //[ 2 ]

方法三:

 // ES6 的 Set 来处理,这是真正按照数学上的集合来进行的,不会有重复元素
var subSet = function(arr1, arr2) {
var set1 = new Set(arr1);
var set2 = new Set(arr2); var subset = []; for (let item of set1) {
if (!set2.has(item)) {
subset.push(item);
}
} return subset;
};
//普通方法
var subSet = function(arr1, arr2) {
var len = arr1.length;
var arr = []; while (len--) {
if (arr2.indexOf(arr1[len]) < 0) {
arr.push(arr1[len]);
}
} return arr;
};

方法四:

 // 数组求差值
var arr1 = [1, 2, 4, 9, 0];
var arr2 = [2, 4, 7, 8]; var difference = function(arr1, arr2) {
var diff = [];
var tmp = arr2; arr1.forEach(function(val1, i){
if (arr2.indexOf(val1) < 0) {
diff.push(val1);
} else {
tmp.splice(tmp.indexOf(val1), 1);
}
}); console.log(diff.concat(tmp));
} // 输出 [ 1, 9, 0, 7, 8 ]
difference(arr1, arr2);
 
04-27 19:46