gpt4 book ai didi

javascript - 如何将数组与数组的数组进行比较?

转载 作者:可可西里 更新时间:2023-11-01 01:42:18 25 4
gpt4 key购买 nike

这是一款井字游戏应用的尝试。我有两个数组 playerMoveswinningCombinations。像这样。

var playerMoves= [0,1,4];
var winningCombinations = [
[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]
];

我需要过滤 winningCombination 数组,使 playerMoves 数组的至少两个值与 winningCombination 中的每个数组匹配>。

findPossibleMove(playerMoves);
// should return [[0,1,2],[1,4,7], [0,4,8] ]

我的尝试

function findPossibleMove(arr){
var found = 0;
return arr.forEach((item)=>{
winningCombinations.map((obj)=>{
if(obj.indexOf(item) !== -1) {
found++;
}
if(found===2){
return obj;
}
})
})
}

最佳答案

三个简单的步骤:

  • 使用indexOf 函数检查winningCombinations 数组子数组中的指定元素是否存在于playerMoves 数组中。
  • 如果是这样 - 使用 Array#filter 函数将其过滤掉。
  • 如果返回的、过滤后的子数组的长度等于 2,这意味着出现了两个(不多也不少)元素 - 它满足我们的条件 - 用另一个 数组#filter

let playerMoves = [0, 1, 4];
let winningCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];

let res = winningCombinations.filter(v => v.filter(c => {
return playerMoves.indexOf(c) > -1;
}).length == 2);

console.log(JSON.stringify(res));

关于javascript - 如何将数组与数组的数组进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152060/

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