方法一:最普遍的做法

使用 ES5 语法来实现虽然会麻烦些,但兼容性最好,不用考虑浏览器 JavaScript 版本。也不用引入其他第三方库。

1,直接使用 filter、concat 来计算

var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
 
//交集
var c = a.filter(function(v){ return b.indexOf(v) > -1 })
 
//差集
var d = a.filter(function(v){ return b.indexOf(v) == -1 })
 
//补集
var e = a.filter(function(v){ return !(b.indexOf(v) > -1) })
        .concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}))
 
//并集
var f = a.concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}));
 
console.log("数组a:", a);
console.log("数组b:", b);
console.log("a与b的交集:", c);
console.log("a与b的差集:", d);
console.log("a与b的补集:", e);
console.log("a与b的并集:", f);

2,对 Array 进行扩展

(1)为方便使用,我们可以对数组功能进行扩展,增加一些常用的方法。

//数组功能扩展
//数组迭代函数
Array.prototype.each = function(fn){
  fn = fn || Function.K;
   var a = [];
   var args = Array.prototype.slice.call(arguments, 1);
   for(var i = 0; i < this.length; i++){
       var res = fn.apply(this,[this[i],i].concat(args));
       if(res != null) a.push(res);
   }
   return a;
};
 
//数组是否包含指定元素
Array.prototype.contains = function(suArr){
  for(var i = 0; i < this.length; i ++){
      if(this[i] == suArr){
          return true;
      }
   }
   return false;
}
 
//不重复元素构成的数组
Array.prototype.uniquelize = function(){
   var ra = new Array();
   for(var i = 0; i < this.length; i ++){
      if(!ra.contains(this[i])){
          ra.push(this[i]);
      }
   }
   return ra;
};
 
//两个数组的交集
Array.intersect = function(a, b){
   return a.uniquelize().each(function(o){return b.contains(o) ? o : null});
};
 
//两个数组的差集
Array.minus = function(a, b){
   return a.uniquelize().each(function(o){return b.contains(o) ? null : o});
};
 
//两个数组的补集
Array.complement = function(a, b){
   return Array.minus(Array.union(a, b),Array.intersect(a, b));
};
 
//两个数组并集
Array.union = function(a, b){
   return a.concat(b).uniquelize();
};
 

(2)使用样例

var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
console.log("a与b的交集:", Array.intersect(a, b));
console.log("a与b的差集:", Array.minus(a, b));
console.log("a与b的补集:", Array.complement(a, b));
console.log("a与b的并集:", Array.union(a, b));

方法二:使用 ES6 语法实现

1,实现原理

而在 ES6 中我们可以借助扩展运算符(...)以及 Set 的特性实现相关计算,代码也会更加简单些。

2,样例代码

var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
 
var sa = new Set(a);
var sb = new Set(b);
 
// 交集
let intersect = a.filter(x => sb.has(x));
 
// 差集
let minus = a.filter(x => !sb.has(x));
 
// 补集
let complement  = [...a.filter(x => !sb.has(x)), ...b.filter(x => !sa.has(x))];
 
// 并集
let unionSet = Array.from(new Set([...a, ...b]));
 
console.log("a与b的交集:", intersect);
console.log("a与b的差集:", minus);
console.log("a与b的补集:", complement);
console.log("a与b的并集:", unionSet);

方法三:使用 jQuery 实现

如果项目中有引入 jQuery,那么实现起来也很简单。

var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
 
// 交集
let intersect = $(a).filter(b).toArray();
 
// 差集
let minus = $(a).not(b).toArray();
 
// 补集
let complement  = $(a).not(b).toArray().concat($(b).not(a).toArray());
 
// 并集
let unionSet = $.unique(a.concat(b));
 
console.log("a与b的交集:", intersect);
console.log("a与b的差集:", minus);
console.log("a与b的补集:", complement);
console.log("a与b的并集:", unionSet);

转自:http://www.hangge.com/blog/cache/detail_1862.html

 
 

1,直接使用 filter、concat 来计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
 
//交集
var c = a.filter(function(v){ return b.indexOf(v) > -1 })
 
//差集
var d = a.filter(function(v){ return b.indexOf(v) == -1 })
 
//补集
var e = a.filter(function(v){ return !(b.indexOf(v) > -1) })
        .concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}))
 
//并集
var f = a.concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}));
 
console.log("数组a:", a);
console.log("数组b:", b);
console.log("a与b的交集:", c);
console.log("a与b的差集:", d);
console.log("a与b的补集:", e);
console.log("a与b的并集:", f);

运行结果如下:

2,对 Array 进行扩展

(1)为方便使用,我们可以对数组功能进行扩展,增加一些常用的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//数组功能扩展
//数组迭代函数
Array.prototype.each = function(fn){
  fn = fn || Function.K;
   var a = [];
   var args = Array.prototype.slice.call(arguments, 1);
   for(var i = 0; i < this.length; i++){
       var res = fn.apply(this,[this[i],i].concat(args));
       if(res != null) a.push(res);
   }
   return a;
};
 
//数组是否包含指定元素
Array.prototype.contains = function(suArr){
  for(var i = 0; i < this.length; i ++){
      if(this[i] == suArr){
          return true;
      }
   }
   return false;
}
 
//不重复元素构成的数组
Array.prototype.uniquelize = function(){
   var ra = new Array();
   for(var i = 0; i < this.length; i ++){
      if(!ra.contains(this[i])){
          ra.push(this[i]);
      }
   }
   return ra;
};
 
//两个数组的交集
Array.intersect = function(a, b){
   return a.uniquelize().each(function(o){return b.contains(o) ? o : null});
};
 
//两个数组的差集
Array.minus = function(a, b){
   return a.uniquelize().each(function(o){return b.contains(o) ? null : o});
};
 
//两个数组的补集
Array.complement = function(a, b){
   return Array.minus(Array.union(a, b),Array.intersect(a, b));
};
 
//两个数组并集
Array.union = function(a, b){
   return a.concat(b).uniquelize();
};

(2)使用样例

1
2
3
4
5
6
7
8
var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
console.log("a与b的交集:", Array.intersect(a, b));
console.log("a与b的差集:", Array.minus(a, b));
console.log("a与b的补集:", Array.complement(a, b));
console.log("a与b的并集:", Array.union(a, b));

(3)运行结果同上面一样。

方法二:使用 ES6 语法实现

1,实现原理

而在 ES6 中我们可以借助扩展运算符(...)以及 Set 的特性实现相关计算,代码也会更加简单些。

2,样例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
 
var sa = new Set(a);
var sb = new Set(b);
 
// 交集
let intersect = a.filter(x => sb.has(x));
 
// 差集
let minus = a.filter(x => !sb.has(x));
 
// 补集
let complement  = [...a.filter(x => !sb.has(x)), ...b.filter(x => !sa.has(x))];
 
// 并集
let unionSet = Array.from(new Set([...a, ...b]));
 
console.log("a与b的交集:", intersect);
console.log("a与b的差集:", minus);
console.log("a与b的补集:", complement);
console.log("a与b的并集:", unionSet);

运行结果还是一样:

方法三:使用 jQuery 实现

如果项目中有引入 jQuery,那么实现起来也很简单。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
 
// 交集
let intersect = $(a).filter(b).toArray();
 
// 差集
let minus = $(a).not(b).toArray();
 
// 补集
let complement  = $(a).not(b).toArray().concat($(b).not(a).toArray());
 
// 并集
let unionSet = $.unique(a.concat(b));
 
console.log("a与b的交集:", intersect);
console.log("a与b的差集:", minus);
console.log("a与b的补集:", complement);
console.log("a与b的并集:", unionSet);

运行结果还是一样:

原文出自:www.hangge.com  转载请保留原文链接:http://www.hangge.com/blog/cache/detail_1862.html

JS - 计算两个数组的交集、差集、并集、补集(多种实现方式)的更多相关文章

  1. js取两个数组的交集|差集|并集|补集|去重示例代码

    http://www.jb51.net/article/40385.htm 代码如下: /** * each是一个集合迭代函数,它接受一个函数作为参数和一组可选的参数 * 这个迭代函数依次将集合的每一 ...

  2. js 获取两个数组的交集,并集,补集,差集

    https://blog.csdn.net/piaojiancong/article/details/98199541 ES5 const arr1 = [1,2,3,4,5], arr2 = [5, ...

  3. python-->(set /dict)交集 差集 并集 补集(功能用来做交差并补的)

    # ### 集合 作用:交集 差集 并集 补集(功能用来做交差并补的) '''特征:自动去重 无序''' #定义一个空集合 setvar = set() #set()强制转换成一个空集合的数据类型 p ...

  4. js求两个数组的交集|并集|差集|去重

    let a = [1,2,3], b= [2, 4, 5]; 1.差集 (a-b 差集:属于a但不属于b的集合)  a-b = [1,3] (b-a 差集:属于b但不属于a的集合)  b-a = [4 ...

  5. C# 数组比较--取得两个集合的交集,差集,并集的方法

    方法关键字: 交集:Intersect 差集:Except 并集:Union 使用代码: , , , , }; , , , , }; var 交集 = arr1.Intersect(arr2).ToL ...

  6. javascript 数组求交集/差集/并集/过滤重复

    最近在小一个小程序项目,突然发现 javscript 对数组支持不是很好,连这些基本的功能,都还要自己封装.网上查了下,再结合自己的想法,封装了一下,代码如下. //数组交集 Array.protot ...

  7. java用最少循环求两个数组的交集、差集、并集

    import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List ...

  8. 6、两个数组的交集 II

    6.两个数组的交集 II 给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入: n ...

  9. 【LeetCode题解】350_两个数组的交集Ⅱ

    目录 [LeetCode题解]350_两个数组的交集Ⅱ 描述 方法一:映射 Java 实现 Python 实现 类似的 Python 实现 方法二:双指针 Java 实现 Python 实现 [Lee ...

随机推荐

  1. webpack请求文件路径代理

    在开发模式下,访问页面请求会跑到根路径,因为写的都  ./images  而index又在根目录, 所以访问地址会是 http://localhost:8080/images/abc.jpg  而实际 ...

  2. vue中修改了数据但视图无法更新的情况(转)

    原文地址:https://blog.csdn.net/qq_39985511/article/details/79778806

  3. spring data jpa 一对多查询

    在一对多关系中,我们习惯把一的一方称之为主表,把多的一方称之为从表.在数据库中建立一对多的关系,需要使用数据库的外键约束. 什么是外键? 指的是从表中有一列,取值参照主表的主键,这一列就是外键. pa ...

  4. Java业务代理模式~

    业务代理模式用于解耦表示层和业务层. 它基本上用于减少表示层代码中的业务层代码的通信或远程查找功能.在业务层有以下实体. 客户端(Client) - 表示层代码可以是JSP,servlet或UI ja ...

  5. Learning OSG programing---osgClip

    OSG Clip例程剖析 首先是创建剪切节点的函数代码: osg::ref_ptr<osg::Node> decorate_with_clip_node(const osg::ref_pt ...

  6. linux中的常用信号

    linux中的常用信号,见如下列表: 信号名 值 标注 解释 ------------------------------------------------------------------ HU ...

  7. [Leetcode] 176.第二高薪水

    题目: 编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) . +----+--------+ | Id | Salary | +----+--------+ | 1 | ...

  8. how to prevent lowmemorykiller from killing processes

    Hi there, I've upgraded a number of test systems to the latest Saucy beta. I've seen quite a few cas ...

  9. How to compile Linux kernel in fedora 6

    前提:已裝好Fedora 6 core 2.6.18 ,在 Fedora 6 中compile linux kernel.1.下載 Fedora 6 core 2.6.18 http://www.ke ...

  10. 通过yum在CentOS7部署LNMP环境(Centos7.4+Nginx1.12+mariadb5.5.56+PHP7.0)

    LNMP环境 CentOS Linux release 7.4.1708 PHP 7.0.25 nginx version: nginx/1.12.2 mariadb: 5.5.56-MariaDB ...