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


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

    //数组交集
    Array.prototype.intersect  = function(){
    
        let mine = this.concat();
        for (var i = 0; i < arguments.length; i++) {
        
            mine.map(function (value, index) {
                if (!this.includes(value)) delete mine[index];
                
            }, arguments[i]);
        }
        
        return mine.filter(v => v);
    };
    
    
    
    //数组差集:返回在当前数组中,但不在其他数组中的元素
    Array.prototype.minus = function(){
    
        let mine = this.concat();
        for (var i = 0; i < arguments.length; i++) {
       
            mine.map(function (value, index) {
                if (this.includes(value))  delete mine[index];
                
            }, arguments[i]);
        }
        return mine.filter(v => v);
    };
    
    
    
    //过滤数组重复元素
    Array.prototype.unique = function(){
    
        let result = [];
         this.map(function (value, index) {
             if (!this.includes(value))   this.push(value);
         }, result);
        
        return result;
    };
    
    
    //数组并集
    Array.prototype.union = function(){
    
        let result = this.concat();
        for (var i = 0; i < arguments.length; i++) {
        
            arguments[i].map(function (value, index) {
                if (!this.includes(value))   this.push(value);
    
            }, result);
        }
       return result;
    };
    
    
    [1, 2, 3, 2, 1].unique();
    [1, 2, 3].intersect([1, 2, 8], [1, 2, 6], [1, 2, 3]);
    [1, 2, 3].minus(["aaaa",  2], [  "cccc", 1]);
    [1, 2, 3].union(["Robin", "aaaa", "bbbb"], ["aaaa", "cccc"]);
  • 相关阅读:
    SpringMVC传参
    mysql JDBC总结
    sql小总结2
    js中frame的操作问题
    httpclient总结
    C#图解教程读书笔记(第1章 C#和.net框架)
    C#图解教程读书笔记(第15章 委托)
    在Ribbon中,中文换行位置不对怎么办
    代码中设置excel自定义格式为[红色]的处理方法
    VSTO安装部署(完美解决XP+2007)
  • 原文地址:https://www.cnblogs.com/zbseoag/p/9952513.html
Copyright © 2020-2023  润新知