返回列表

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

默认分类 2018/01/02 04:42

注:只实现了去重,交集,差集,并集=A+(B-A) 补集=B-A

示例如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>haiyang.me - 集合操作</title>
</head>
<body>
<script>
  // 去重
  Array.prototype.unique = function(copy) {
    var list1 = this
    list1.reverse()
    var list2 = []
    for (var i = list1.length - 1; i > -1; i--) {
      var item = copy === 'copy' ? list1[i] : list1.pop()
      var exist = false
      for (var j = list2.length - 1; !exist && j > -1; j--) {
        if ('number,string'.indexOf(typeof item) > -1 && 'number,string'.indexOf(typeof list2[j]) > -1) {
          if (String(item) === String(list2[j])) {
            if (typeof item === 'number') list2[j] = item
            exist = true
          }
        } else if (item === list2[j]) exist = true
      }
      if (!exist) list2.push(item)
    }

    if (copy === 'copy') {
      this.reverse()
      return list2
    } else {
      for (var j = list2.length - 1; j > -1; j--) this.push(list2[j])
      this.reverse()
      return this
    }
  }
  // 交集 (相同部分)
  Array.prototype.joint = function(list2, copy) {
    if (Object.prototype.toString.call(list2) !== '[object Array]') return this
    var list1 = this
    var res = []
    for (var i = list1.length - 1; i > -1; i--) {
      var item = list1[i]
      var exist = false
      for (var j = list2.length - 1; !exist && j > -1; j--) {
        if ('number,string'.indexOf(typeof item) > -1 && 'number,string'.indexOf(typeof list2[j]) > -1) {
          if (String(item) === String(list2[j])) exist = true
        } else if (item === list2[j]) exist = true
      }
      if (exist) res.push(item)
    }
    if (copy === 'copy') {
      res.reverse()
      return res
    }
    else {
      this.length = 0
      for (var j = res.length - 1; j > -1; j--) this.push(res[j])
      return this
    }
  }
  // 差集 (去掉 相同部分 剩下的源集合)
  Array.prototype.sub = function(list2, copy) {
    if (Object.prototype.toString.call(list2) !== '[object Array]') return this
    var list1 = this
    var res = []
    for (var i = list1.length - 1; i > -1; i--) {
      var item = list1[i]
      var exist = false
      for (var j = list2.length - 1; !exist && j > -1; j--) {
        if ('number,string'.indexOf(typeof item) > -1 && 'number,string'.indexOf(typeof list2[j]) > -1) {
          if (String(item) === String(list2[j])) exist = true
        } else if (item === list2[j]) exist = true
      }
      if (!exist) res.push(item)
    }
    if (copy === 'copy') {
      res.reverse()
      return res
    }
    else {
      this.length = 0
      for (var j = res.length - 1; j > -1; j--) this.push(res[j])
      return this
    }
  }
  // 并集可以直接用concat加unique
  var aa = [1, 2, 3, '1', '4', null, undefined, null, -0, '-0'], bb = ['1', null, undefined]
  console.log(aa.joint(bb, 'copy'))
  console.log(aa.sub(bb, 'copy'))
</script>

</body>
</html>