zoukankan      html  css  js  c++  java
  • 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"]);
  • 相关阅读:
    内置函数(少量)
    画国旗(尺寸不标准)
    测试题——程序
    乱码笔记2--字典
    列表
    课堂笔记 ——————乱
    如何利用pip安装国内镜像源
    pip常用指令
    pip卸载
    pip简介
  • 原文地址:https://www.cnblogs.com/zbseoag/p/9952513.html
Copyright © 2011-2022 走看看