js Array 交集 并集 差集 去重

最劲项目需要用到js数组去重和交集的一些运算,我的数组元素个数可能到达1000以上,网上的实现方式都是2次循环,性能不适合我的需求,1000*1000那循环次数太多了,所以我这里采用对象object来做处理,用空间换时间,code 如下:

        ///集合取交集
Array.intersect = function () {
var result = new Array();
var obj = {};
for (var i = ; i < arguments.length; i++) {
for (var j = ; j < arguments[i].length; j++) {
var str = arguments[i][j];
if (!obj[str]) {
obj[str] = ;
}
else {
obj[str]++;
if (obj[str] == arguments.length)
{
result.push(str);
}
}//end else
}//end for j
}//end for i
return result;
} //集合去掉重复
Array.prototype.uniquelize = function () {
var tmp = {},
ret = [];
for (var i = , j = this.length; i < j; i++) {
if (!tmp[this[i]]) {
tmp[this[i]] = ;
ret.push(this[i]);
}
} return ret;
}
//并集
Array.union = function () {
var arr = new Array();
var obj = {};
for (var i = ; i < arguments.length; i++) {
for (var j = ; j < arguments[i].length; j++)
{
var str=arguments[i][j];
if (!obj[str])
{
obj[str] = ;
arr.push(str);
}
}//end for j
}//end for i
return arr;
} //2个集合的差集 在arr不存在
Array.prototype.minus = function (arr) {
var result = new Array();
var obj = {};
for (var i = ; i < arr.length; i++) {
obj[arr[i]] = ;
}
for (var j = ; j < this.length; j++) {
if (!obj[this[j]])
{
obj[this[j]] = ;
result.push(this[j]);
}
}
return result;
}; console.log(Array.intersect(["", "", ""], ["", "", "", "", ""]));//[2,3]
console.log([, , , , , , , ].uniquelize());//[1,2,3,4,5,6]
console.log(Array.union(["", "", ""], ["", "", "", "", ""], ["", "", "", "", ""]))
console.log(["", "", "", "", ""].minus(["", "", ""]));
上一篇:Windows 10 & change DNS


下一篇:洛谷T21778 过年