当前位置:Gxlcms > JavaScript > JS数组交集、并集、差集的示例代码

JS数组交集、并集、差集的示例代码

时间:2021-07-01 10:21:17 帮助过:23人阅读

 本文介绍了JS数组交集、并集、差集,分享给大家,具体如下:

由于下面会用到ES5的方法,低版本会存在兼容,先应添加对应的polyfill

  1. Array.prototype.indexOf = Array.prototype.indexOf || function (searchElement, fromIndex) {
  2. var index = -1;
  3. fromIndex = fromIndex * 1 || 0;
  4. for (var k = 0, length = this.length; k < length; k++) {
  5. if (k >= fromIndex && this[k] === searchElement) {
  6. index = k;
  7. break;
  8. }
  9. }
  10. return index;
  11. };
  12. Array.prototype.filter = Array.prototype.filter || function (fn, context) {
  13. var arr = [];
  14. if (typeof fn === "function") {
  15. for (var k = 0, length = this.length; k < length; k++) {
  16. fn.call(context, this[k], k, this) && arr.push(this[k]);
  17. }
  18. }
  19. return arr;
  20. };

依赖数组去重方法:

  1. // 数组去重
  2. Array.prototype.unique = function() {
  3. var n = {}, r = [];
  4. for (var i = 0; i < this.length; i++) {
  5. if (!n[this[i]]) {
  6. n[this[i]] = true;
  7. r.push(this[i]);
  8. }
  9. }
  10. return r;
  11. }

交集

交集元素由既属于集合A又属于集合B的元素组成

  1. Array.intersect = function(arr1, arr2) {
  2. if(Object.prototype.toString.call(arr1) === "[object Array]" && Object.prototype.toString.call(arr2) === "[object Array]") {
  3. return arr1.filter(function(v){
  4. return arr2.indexOf(v)!==-1
  5. })
  6. }
  7. }
  8. // 使用方式
  9. Array.intersect([1,2,3,4], [3,4,5,6]); // [3,4]

并集

并集元素由集合A和集合B中所有元素去重组成

  1. Array.union = function(arr1, arr2) {
  2. if(Object.prototype.toString.call(arr1) === "[object Array]" && Object.prototype.toString.call(arr2) === "[object Array]") {
  3. return arr1.concat(arr2).unique()
  4. }
  5. }
  6. // 使用方式
  7. Array.union([1,2,3,4], [1,3,4,5,6]); // [1,2,3,4,5,6]

差集

A的差集:属于A集合不属于B集合的元素

B的差集:属于B集合不属于A集合的元素

  1. Array.prototype.minus = function(arr) {
  2. if(Object.prototype.toString.call(arr) === "[object Array]") {
  3. var interArr = Array.intersect(this, arr);// 交集数组
  4. return this.filter(function(v){
  5. return interArr.indexOf(v) === -1
  6. })
  7. }
  8. }
  9. // 使用方式
  10. var arr = [1,2,3,4];
  11. arr.minus([2,4]); // [1,3]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行