javascript - 获取两个数组中具有匹配值的对象

标签 javascript arrays

我正在玩拉米纸牌。我需要获取与两个对象属性(cardsuitcard 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);

输出:

enter image description here

关于javascript - 获取两个数组中具有匹配值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34428668/

相关文章:

JavaScript 输入字段在加载时获取旧值

c - 大阵列上的段错误

Python:使用正则表达式创建不重复条目的数组

java - java中的多维数据结构

python - 使用 python 和 numpy 创建三阶张量

c - 如何知道两种方法是否对同一数据的不同表示做同样的事情

facebook - Facebook friends_get 函数的问题

javascript - 将行为应用于具有相同类的元素中的特定 div

javascript - 从文档库中获取文件名

javascript - 在回调 AngularJS ng-click 样式中执行 fn(param1, param2)