1

我想分享以下代码,它比较了两个数组数组:-

var x = [["x", "r", "t"], ["a", "b", "n"], ["j", "l", "x"]];
var y = [["y", "w", "z"], ["a", "b", "n"], ["j", "l", "x"]];
var objX = [];
var objY = [];
for (var i = 0; i < x.length; i++)
{
    objX[i] = {};
    for (var j = 0; j < x[i].length; j++)
    {
        objX[i][x[i][j]] = i;
    }

}

for (var i = 0; i < y.length; i++)
{
    objY[i] = {};
    for (var j = 0; j < y[i].length; j++)
    {
        objY[i][y[i][j]] = i;
    }

}
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key))
            size++;
    }
    return size;
};
function compareObjs(oA, oB)
{
    if (Object.size(oA) > Object.size(oB))
    {
        aa = oA;
        ba = oB;
    }
    else
    {
        aa = oB;
        ba = oA;
    }
    for (var property in aa) {
        if (!ba.hasOwnProperty(property)) {
            return false;
        }
    }
    return true;
}
function compareArrayOfObj(aA, aB)
{
    var aIb = [];
    var aMb = [];
    var bMa = [];
    var aIIndex = [];
    var bIIndex = [];
    var aIF = [];
    var bIF = [];
    if (aA.length > aB.length)
    {
        a = aA;
        b = aB;
    }
    else
    {
        a = aB;
        b = aA;
    }
    for (var i in a)
    {
        for (var j in b)
        {

            if (compareObjs(a[i], b[j]))
            {
                for (var blah in a[i])
                {
                    aIb.push(x[a[i][blah]]);
                    break;
                }
                aIIndex.push(i);
                bIIndex.push(j);

            }
        }
    }
    for (var i in a)
    {
        if (aIIndex.indexOf(i) == -1)
        {
            for (var blah in a[i])
            {
                aIF.push(x[a[i][blah]]);
                break;
            }
        }
    }
    for (var j in b)
    {
        if (bIIndex.indexOf(j) == -1)
        {
            for (var blah in b[j])
            {
                bIF.push(y[b[j][blah]]);
                break;
            }
        }
    }


    return  {"aIb": aIb, "aMb": aIF, "bMa": bIF}
}

resultSet=compareArrayOfObj(objX, objY);




/*
resultSet object holds three properties as:-

1. aIb = objX Intersection objY 
2. aMb = objX - objY 
3. bMa = objY - objX
*/

代码中的即兴创作总是受欢迎的。基本上我已经编写了这段代码来对数组进行设置操作。它将返回 A 减 B、B 减 A 和 A 交点 B。

4

0 回答 0