时间:2021-07-01 10:21:17 帮助过:23人阅读
本文介绍了JS数组交集、并集、差集,分享给大家,具体如下:
由于下面会用到ES5的方法,低版本会存在兼容,先应添加对应的polyfill
- Array.prototype.indexOf = Array.prototype.indexOf || function (searchElement, fromIndex) {
- var index = -1;
- fromIndex = fromIndex * 1 || 0;
- for (var k = 0, length = this.length; k < length; k++) {
- if (k >= fromIndex && this[k] === searchElement) {
- index = k;
- break;
- }
- }
- return index;
- };
- Array.prototype.filter = Array.prototype.filter || function (fn, context) {
- var arr = [];
- if (typeof fn === "function") {
- for (var k = 0, length = this.length; k < length; k++) {
- fn.call(context, this[k], k, this) && arr.push(this[k]);
- }
- }
- return arr;
- };
依赖数组去重方法:
- // 数组去重
- Array.prototype.unique = function() {
- var n = {}, r = [];
- for (var i = 0; i < this.length; i++) {
- if (!n[this[i]]) {
- n[this[i]] = true;
- r.push(this[i]);
- }
- }
- return r;
- }
交集
交集元素由既属于集合A又属于集合B的元素组成
- Array.intersect = function(arr1, arr2) {
- if(Object.prototype.toString.call(arr1) === "[object Array]" && Object.prototype.toString.call(arr2) === "[object Array]") {
- return arr1.filter(function(v){
- return arr2.indexOf(v)!==-1
- })
- }
- }
- // 使用方式
- Array.intersect([1,2,3,4], [3,4,5,6]); // [3,4]
并集
并集元素由集合A和集合B中所有元素去重组成
- Array.union = function(arr1, arr2) {
- if(Object.prototype.toString.call(arr1) === "[object Array]" && Object.prototype.toString.call(arr2) === "[object Array]") {
- return arr1.concat(arr2).unique()
- }
- }
- // 使用方式
- Array.union([1,2,3,4], [1,3,4,5,6]); // [1,2,3,4,5,6]
差集
A的差集:属于A集合不属于B集合的元素
B的差集:属于B集合不属于A集合的元素
- Array.prototype.minus = function(arr) {
- if(Object.prototype.toString.call(arr) === "[object Array]") {
- var interArr = Array.intersect(this, arr);// 交集数组
- return this.filter(function(v){
- return interArr.indexOf(v) === -1
- })
- }
- }
- // 使用方式
- var arr = [1,2,3,4];
- arr.minus([2,4]); // [1,3]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。