JS实现集合的交集、补集、差集、去重运算示例【

///集合取交集 Array.intersect = function () { var result = new Array(); var obj = {}; for (var i = 0; i < arguments.length; i++) { for (var j = 0; j < arguments[i].length; j++) { var str = arguments[i][j]; if (!obj[str]) { obj[str] = 1; } else { obj[str]++; if (obj[str] == arguments.length) { result.push(str); } } } } return result; } //集合去掉重复 Array.prototype.uniquelize = function () { var tmp = {}, ret = []; for (var i = 0, j = this.length; i < j; i++) { if (!tmp[this[i]]) { tmp[this[i]] = 1; ret.push(this[i]); } } return ret; } //并集 Array.union = function () { var arr = new Array(); var obj = {}; for (var i = 0; i < arguments.length; i++) { for (var j = 0; j < arguments[i].length; j++) { var str=arguments[i][j]; if (!obj[str]) { obj[str] = 1; 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 = 0; i < arr.length; i++) { obj[arr[i]] = 1; } for (var j = 0; j < this.length; j++) { if (!obj[this[j]]) { obj[this[j]] = 1; result.push(this[j]); } } return result; }; console.log(Array.intersect(["1", "2", "3"], ["2", "3", "4", "5", "6"]));//[2,3] console.log([1, 2, 3, 2, 3, 4, 5, 6].uniquelize());//[1,2,3,4,5,6] console.log(Array.union(["1", "2", "3"], ["2", "3", "4", "5", "6"], ["5", "6", "7", "8", "9"])) console.log(["2", "3", "4", "5", "6"].minus(["1", "2", "3"]));

 使用在线HTML/CSS/JavaScript代码运行工具册数上述代码,可得如下运行结果:

JS实现集合的交集、补集、差集、去重运算示例【

ES6写法:使用构造函数Set

const arr1 = [1,2,3,4]; const arr2 = [3,4,5,6]; const arr3 = [1,2,3,2,1,3,4]; let s1 = new Set(arr1); let s2 = new Set(arr2); //并集 let union = [...s1, ...s2]; console.log(union); //[1, 2, 3, 4, 3, 4, 5, 6] //交集 let intersect = arr1.filter( x => s2.has(x) ); console.log(intersect); //[3, 4] //差集 let difference = arr1.filter( x => !s2.has(x) ); console.log(difference); //[1, 2] //去重 let minus = [...new Set(arr3)]; console.log(minus); //[1, 2, 3, 4]

使用在线HTML/CSS/JavaScript代码运行工具册数上述代码,可得如下运行结果:

JS实现集合的交集、补集、差集、去重运算示例【

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数组操作技巧总结》、《JavaScript排序算法总结》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/eac2742a4b959f0f967e74081e53fb2d.html