我正在玩拉米纸牌。我需要获取与两个对象属性(cardsuit
和 card value
)在两组数组中匹配的所有对象。
数组A:
[
{
suit : 'spades',
value : 13
},
{
suit : 'hearts',
value : 8
},
...
]
数组B
[
{
suit : 'spades',
value : 11
},
{
suit : 'hearts',
value : 8
},
...
]
结果将是一个数组:
[
{
suit : 'hearts',
value : 8
},
]
我发现这篇关于使用函数式编程和分组的文章,然后使用 for in
来检查相等性:
An efficient way to get the difference between two arrays of objects?
然而,这似乎是基于单一属性。
所以我尝试了:
var test_hand = testHand(Control_Panel.test_hand);
var bValues = {};
test_hand.forEach(function (test_card) {
bValues[test_card.value] = test_card;
bValues[test_card.suit] = test_card;
});
var tester = this.deck.filter(function (card) {
return (card.value in bValues) && (card.suit in bValues);
});
但显然这将返回 2 倍数量的卡片。
有什么想法吗?
最佳答案
试试这个:
var a = [{
suit: 'spades',
value: 13
}, {
suit: 'hearts',
value: 8
}];
var b = [{
suit: 'spades',
value: 11
}, {
suit: 'hearts',
value: 8
},
];
var result = a.filter(function(v) {
return b.filter(function(v2) {
return (v.suit === v2.suit && v.value === v2.value);
}).length > 0;
});
console.log(result);
输出:
关于javascript - 获取两个数组中具有匹配值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34428668/