Compare arrays as (multi-) sets

前端 未结 8 1655
梦如初夏
梦如初夏 2021-01-04 21:42

I\'m looking for an efficient way to find out whether two arrays contain same amounts of equal elements (in the == sense), in any order:

foo = {         


        
8条回答
  •  迷失自我
    2021-01-04 21:50

    Like this perhaps?

    var foo = {}; var bar=[];
    var a = [3,2,1,foo]; var b = [foo,1,2,3];
    
    function comp(a,b)
    {
        // immediately discard if they are of different sizes
        if (a.length != b.length) return false;
    
        b = b.slice(0); // clone to keep original values after the function
    
        a.forEach(function(e) {
            var i;
            if ((i = b.indexOf(e)) != -1)
                b.splice(i, 1);
        });
    
        return !b.length;
    }
    
    comp(a,b);
    

提交回复
热议问题