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"]);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM