数组的交集,并集,差集的实现,以及Set对象的交集,并集,差集的详细介绍和使用

270 阅读3分钟

【JavaScript】---- 数组的交集,并集,差集的实现,以及Set对象的交集,并集,差集的详细介绍和使用

1. 前言

数组的交集,并集,差集的实现。其实本质来说都不算难,但是 Set 类直接实现这些方法,所以我们先自己实现一下,然后再讲解一下 Set 类的相同方法。

2. intersection 交集

用数学公式,交集被表示为: AB={xAxB}A \cap B = \{x \in A \mid x \in B\}

使用图形表示就是: 输入图片说明

交集:就是给定两个数组,返回两个数组的相同数据项。

2.1 数组方法实现

通过 filter 方法实现。过滤数组1在数组2中存在的数据项,这样的结果就返回的数据项同时都在两个数组中。

  const intersection = (arr1, arr2) => {
    return arr1.filter(item => arr2.includes(item));
  };

2.2 测试

console.log(intersection([1, 2, 3, 4, 5], [4, 5, 6, 7, 8])); // [4, 5]

2.3 测试结果

输入图片说明

2.4 Set.intersection

使用语法:

new Set(arr1).intersection(new Set(arr2))

由于是 Set 类的方法,因此需要将数组转换为 Set 对象,然后再调用 Set 对象的 intersection 方法,进行交集的获取。最后返回的是交集的 Set 对象,需要再转换为数组操作。

2.5 测试

const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
const result = odds.intersection(squares);
console.log(result ); // Set(2) { 1, 9 }
console.log([...result ])

2.6 测试结果

输入图片说明

3. union 并集

用数学公式,并集被表示为: AB={xxA or xB}A \cup B = \{x \mid x \in A \text{ or } x \in B\}

使用图形表示就是: 输入图片说明

并集:并集就是将两个数组合并,并去重。

3.1 使用 reduce 和 includes 的实现

  1. 先使用数组的扩展符,将两个数组进行合并;
  2. 然后使用 reduce 方法遍历,查找当前元素是否已经存在,不存在就放入。
  const union = (arr1, arr2) => {
    const combined = [...arr1, ...arr2];
    return combined.reduce((acc, item) => {
      if (!acc.includes(item)) {
        acc.push(item);
      }
      return acc;
    }, []);
  }

3.2 测试

console.log(union([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]));

3.3 测试结果

输入图片说明

3.4 Set.union

使用语法:

new Set(arr1).union(new Set(arr2))

3.5 测试

const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
const result = odds.union(squares);
console.log(result );
console.log([...result ])

3.6 测试结果

输入图片说明

4. difference 差集

用数学公式,差集被表示为: AB={xAxB}A \setminus B = \{x \in A \mid x \notin B\}

使用图形表示就是: 输入图片说明

差集:就是表示返回的数据项在A数据集中能找到,在B数据集中没有。

4.1 使用 filter 和 includes 实现

  const difference = (arr1, arr2) => {
    return arr1.filter(item => !arr2.includes(item));
  }

4.2 测试

console.log(difference([1, 2, 3, 4, 5], [4, 5, 6, 7, 8])); 

4.3 测试结果

输入图片说明

4.4 Set.difference

使用语法:

new Set(arr1).difference(new Set(arr2))

4.5 测试

const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
const result = odds.difference(squares);
console.log(result );
console.log([...result ])

4.6 测试结果

输入图片说明

5. 总结

  1. Set 类的方法,每次都需要我们将数组转换为 Set 对象,做了对应操作后,再转会数组。
  2. 我们自己通过数组方法实现,需要对返回结果去重操作,我这里的 difference 和 intersection 没有进行去重操作。
  3. Set 还提供一些其他数据集的操作,比如 symmetricDifference (方法接收一个集合,并返回一个新的集合,这个新集合包含的元素要么在这个集合中要么在给定的集合中,但不能同时在两个集合中。)、isDisjointFrom (接收一个集合作为参数,并返回一个布尔值,该值表示此集合与给定的集合是否没有共同的元素。)等,MDN 文档中都有示例和图示,使用时查询即可。

6. 兼容性

输入图片说明

7. 兼容性解决

Polyfill:https://github.com/zloirock/core-js#new-set-methods Shim:https://github.com/rauschma/set-methods-polyfill

8. 其他

这篇文章的名字早就写在笔记本上了,一直准备写。直到昨天,《认知觉醒》看到清晰力里边,要求将第二天需要做的事情,按照重要程度,进行一个列表标记,今天才开始写出来,哎,真的是知易行难。知行合一的行在我这里还是有待加强。 加油!!!