gpt4 book ai didi

javascript - 两个数组之间除一个属性外的对象的交集

转载 作者:行者123 更新时间:2023-12-03 21:17:32 25 4
gpt4 key购买 nike

我有两个包含相同类型对象的数组(相同的属性但关联的值不同)。我想比较这两个数组并匹配除一个属性外相等的对象。然后我想在第一个数组中找到匹配的对象的索引,以便将这些对象插入不同的数组。

我认为所有这些都可以使用 lodash 来完成,我想避免 for 循环,以便尽可能提高效率

注意我是在js类工作

这是我的尝试(无效)

class MatchPlayers {
constructor(){
this.TeamA = [
{weight:'75',height:'170', foot:'Left', available:true},
{weight:'88',height:'190', foot:'Right', available:true},
{weight:'65',height:'163', foot:'Right', available:false},
{weight:'70',height:'168', foot:'Left', available:true}
]

this.TeamB = [
{weight:'75',height:'170', foot:'', available:true},
{weight:'93',height:'201', foot:'', available:true},
{weight:'65',height:'163', foot:'', available:false}
]

this.MatchedPlayers = []
}

PlayersMatch (){
for(this.i=0;this.i<this.TeamA.length;this.i++){
if (_.intersection(this.TeamA,{weight:this.TeamB.weight, height:this.TeamB.height, available:this.TeamB.available})){
this.position = _.findIndex(this.TeamA,{weight:this.TeamB.weight, height:this.TeamB.height, available:this.TeamB.available})
this.MatchedPlayers.push(this.TeamA[this.position])
} else {console.log('No matchable players')}
}
console.log(this.MatchedPlayers)
}
}

在这种情况下,我想匹配除“foot”之外具有相同属性的对象,因此预期输出为:

//Expected Output:
this.MatchedPlayers = [
{weight:'75',height:'170', foot:'Left', available:true},
{weight:'65',height:'163', foot:'Right', available:false}
]

最佳答案

您可以采用一种简化的方法并省略 foot 属性,并通过 _.isEqual 获取 lefot over 属性的交集。

var a = [{ weight: '75', height: '170', foot: 'Left', available: true }, { weight: '88', height: '190', foot: 'Right', available: true }, { weight: '65', height: '163', foot: 'Right', available: false }, { weight: '70', height: '168', foot: 'Left', available: true }],
b = [{ weight: '75', height: '170', foot: '', available: true }, { weight: '93', height: '201', foot: '', available: true }, { weight: '65', height: '163', foot: '', available: false }],
omitFoot = o => _.omit(o, 'foot'),
intersection = _.intersectionWith(
_.map(a, omitFoot),
_.map(b, omitFoot),
_.isEqual
);

console.log(intersection);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

关于javascript - 两个数组之间除一个属性外的对象的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com