get difference between two arrays (including duplicates)

前端 未结 6 1794
终归单人心
终归单人心 2021-01-12 04:14

I see a lot of posts about how to get the difference and symmetric difference of an array in javascript, but I haven\'t found anything on how to find the difference, includi

6条回答
  •  有刺的猬
    2021-01-12 04:55

        Array.prototype.Diff = function( secondArray ) {
        var mergedArray = this.concat( secondArray );
        var mergedString = mergedArray.toString();
        var finalArray = new Array();
    
        for( var i = 0; i < mergedArray.length; i++ ) {
            if(mergedString.match(mergedArray[i])) {
                finalArray.push(mergedArray[i]);
                mergedString = mergedString.replace(new RegExp(mergedArray[i], "g"), "");
            }
        }
        return finalArray;
    }
    
    var let = [ 1 ];
    var updated = [ 1, 1, 2 ];
    
    console.log(let.Diff(updated));
    

    I like the prototype way. You can save the prototype function above in a JS file and import in any page that you want, the it's possible to use as an embedded function to the object (Array for this case).

提交回复
热议问题