zoukankan      html  css  js  c++  java
  • JS数组交集并集差集补集

    ///集合取交集
    Array.intersect = function () {
    var result = new Array();
    var obj = {};
    for (var i = 0; i < arguments.length; i++) {
    for (var j = 0; j < arguments[i].length; j++) {
    var str = arguments[i][j];
    if (!obj[str]) {
    obj[str] = 1;
    }
    else {
    obj[str]++;
    if (obj[str] == arguments.length)
    {
    result.push(str);
    }
    }//end else
    }//end for j
    }//end for i
    return result;
    }

    //集合去掉重复
    Array.prototype.uniquelize = function () {
    var tmp = {},
    ret = [];
    for (var i = 0, j = this.length; i < j; i++) {
    if (!tmp[this[i]]) {
    tmp[this[i]] = 1;
    ret.push(this[i]);
    }
    }

    return ret;
    }
    //并集
    Array.union = function () {
    var arr = new Array();
    var obj = {};
    for (var i = 0; i < arguments.length; i++) {
    for (var j = 0; j < arguments[i].length; j++)
    {
    var str=arguments[i][j];
    if (!obj[str])
    {
    obj[str] = 1;
    arr.push(str);
    }
    }//end for j
    }//end for i
    return arr;
    }

    //2个集合的差集 在arr不存在
    Array.prototype.minus = function (arr) {
    var result = new Array();
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
    obj[arr[i]] = 1;
    }
    for (var j = 0; j < this.length; j++) {
    if (!obj[this[j]])
    {
    obj[this[j]] = 1;
    result.push(this[j]);
    }
    }
    return result;
    };

    console.log(Array.intersect(["1", "2", "3"], ["2", "3", "4", "5", "6"]));//[2,3]
    console.log([1, 2, 3, 2, 3, 4, 5, 6].uniquelize());//[1,2,3,4,5,6]
    console.log(Array.union(["1", "2", "3"], ["2", "3", "4", "5", "6"], ["5", "6", "7", "8", "9"]))
    console.log(["2", "3", "4", "5", "6"].minus(["1", "2", "3"]));

  • 相关阅读:
    python內建模块之datetime
    python实现两个经纬度点之间的距离和方位角
    Python实现DBScan
    关于sru源码class Model的parameters
    pytorch之LSTM
    pytorch对可变长度序列的处理
    pytorch函数之torch.normal()
    PyTorch学习系列(九)——参数_初始化
    ubuntu16.04系统搜狗输入法的安装
    Scala 匿名函数
  • 原文地址:https://www.cnblogs.com/shenbo666/p/11051467.html
Copyright © 2011-2022 走看看