简体   繁体   English

检查来自不同数组的两个元素的一个属性是否相等?

[英]Check if one property of two elements from different arrays are equal?

At present I've been using nested for loops to solve this issue:目前我一直在使用嵌套的 for 循环来解决这个问题:

for (var i = 0; i < this.props.trackedPlayers.length; i++)
{
    for (var j = 0; j < PHP_VARS.players_data.length; j++)
    {
        // This check here is the key part
        if (PHP_VARS.players_data[j]._id == this.props.trackedPlayers[i]._id)
        {
            data.push(// stuff from both arrays..);
        }
    }
}

However I figured there might be a boilerplate function that does this already.但是我认为可能已经有一个样板函数可以做到这一点。 Done a few searches but nothing cropped up - any pointers, or is this the best I've got for now?进行了几次搜索,但没有任何结果 - 任何提示,或者这是我目前最好的吗?

EDIT: Brief explanation, trackedPlayers are all from players_data.编辑:简要说明,trackedPlayers 均来自players_data。 By checking if each player in the (generally) larger players_data is in trackedPlayers, I know whether or not to list them as an option for 'adding' to an HTML select field.通过检查(通常)较大的players_data 中的每个玩家是否在trackedPlayers 中,我知道是否将它们列为“添加”到HTML 选择字段的选项。

You could use an object as hash table and iterate over both arrays, first for the building of the hash table and the second for test and further operations.您可以使用一个对象作为哈希表并遍历两个数组,首先用于构建哈希表,第二次用于测试和进一步操作。

var object = Object.create(null);
this.props.trackedPlayers.forEach(function (a) {
    object[a._id] = a;
});
PHP_VARS.players_data.forEach(function (a) {
    if (object[a._id]) {
        // access data from this.props.trackedPlayers
        // with object[a._id]._id as example
        // access data from  PHP_VARS.players_data
        // with a._id as example
        data.push(/* stuff from both arrays..*/);
    }
});

lodash library has _.intersectionBy() function which does exactly what you want. lodash 库有_.intersectionBy()函数,它完全符合你的要求。 Using this, you could change your code to that:使用它,您可以将代码更改为:

_.intersectionBy([PHP_VARS.players_data, this.props.trackedPlayers], "_id")
  .forEach(element=> {
    data.push(/* ... */)
  })

or, using for...of loop:或者,使用for...of循环:

const intersection = _.intersectionBy([PHP_VARS.players_data, this.props.trackedPlayers], "_id")
for (element of intersection) {
  data.push(/* ... */)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM