var arr1 =['Five','Four','Full','Straight','Three','Two','One','Bust']
var arr2 = [{player1-box: "One"},{player2-box: "One"},{player3-box: "Four"},{player1-box: "Three"},{player2-box: "Three"},{player3-box: "Two"},{player1-box: "Five"},{player2-box: "One"},{player3-box: "One"}]
我有两个如上所述的数组。 我的要求是比较两个数组,并从第二个数组中获取第一个匹配值。 在此示例中,arr1中的值“ FIVE”将匹配第二个数组arr2中第7个索引中的值
意味着我将获得像{player1-box:“ Five”}}这样的键和值? 有人可以调查一下并让我知道吗?
谢谢..
答案 0 :(得分:3)
如果在arr1
中用Array#some
找到了一个对象,则可以用Array#find
迭代arr2
并退出循环。
虽然对象具有不同的键,但是您需要获取用于检查的值。
var arr1 = ['Five', 'Four', 'Full', 'Straight', 'Three', 'Two', 'One', 'Bust'],
arr2 = [{ "player1-box": "One" }, { "player2-box": "One" }, { "player3-box": "Four" }, { "player1-box": "Three" }, { "player2-box": "Three" }, { "player3-box": "Two" }, { "player1-box": "Five" }, { "player2-box": "One" }, { "player3-box": "One" }],
result;
arr1.some(v => result = arr2.find(o => Object.values(o).includes(v)));
console.log(result);
没有arrow functions和ES6部分。
var arr1 = ['Five', 'Four', 'Full', 'Straight', 'Three', 'Two', 'One', 'Bust'],
arr2 = [{ "player1-box": "One" }, { "player2-box": "One" }, { "player3-box": "Four" }, { "player1-box": "Three" }, { "player2-box": "Three" }, { "player3-box": "Two" }, { "player1-box": "Five" }, { "player2-box": "One" }, { "player3-box": "One" }],
result;
arr1.some(function (v) {
return arr2.some(function (o) {
if (Object.keys(o).some(function (k) { return v === o[k]; })) {
return result = o;
}
});
});
console.log(result);
答案 1 :(得分:1)
除了遍历arr1之外,我看不到当前数据设置的任何方式。如果找不到,则将返回arr1
的{{1}}中的第一个。
undefined
如果有平局的可能,可以使用var arr1 =['Five','Four','Full','Straight','Three','Two','One','Bust']
var arr2 = [{'player1-box': "One"},{'player2-box': "One"},{'player3-box': "Four"},{'player1-box': "Three"},{'player2-box': "Three"},{'player3-box': "Two"},{'player1-box': "Five"},{'player2-box': "One"},{'player3-box': "One"}]
function findFirst(keys, players){
for (key of keys){
let player = players.find(player => Object.values(player).includes(key))
if (player) return player
}
}
let first = findFirst(arr1, arr2)
console.log(first)
代替filter()
并返回一个数组:
find()