0

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"} 这样的键和值?有人可以调查一下并告诉我吗?

谢谢..

4

2 回答 2

3

如果在with中找到对象,您可以迭代arr1Array#some退出循环。arr2Array#find

虽然对象有不同的键,但您需要获取值进行检查。

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);

没有箭头函数和 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);

于 2018-11-11T18:12:05.010 回答
1

除了迭代 arr1 之外,我看不到当前数据设置的任何方法。如果没有找到,这将返回第一个找到arr1的。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()并返回一个数组:

var arr1 =['Five','Four','Full','Straight','Three','Two','One','Bust']
var arr2 = [{'player1-box': "One"},{'player2-box': "Five"},{'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.filter(player => Object.values(player).includes(key))
        if (player) return player
    }
}
console.log(findFirst(arr1, arr2))

于 2018-11-11T18:14:27.923 回答