以下代码我想分享比较两个数组的数组: -
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.