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

16

这是一个井字棋游戏应用的尝试。 我有两个数组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;
      }        
    })
  })      
}
3个回答

12

三个简单的步骤:

  • 使用 indexOf 函数检查 winningCombinations 数组子数组中指定元素是否存在于 playerMoves 数组中。
  • 如果存在,则使用 Array#filter 函数过滤掉它。
  • 如果返回的过滤后的子数组长度等于 2,则表示两个(不多不少)元素已出现 - 符合我们的条件 - 再次使用另一个 Array#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));


你会如何替换不匹配的元素,而不是过滤掉它们?比如说,如果我有一个数组 [['WA', 0], [OR, 0]],另一个数组是 [['WA', 1], [OR, 0]],我想要将第一个数组中的 WA 替换为第二个数组中的 WA 值。 - Tim Bogdanov

3
你可以使用 filterincludes 来实现这个目标:

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

var filteredCombinations = winningCombinations.filter((combination) =>
  combination.filter(x => playerMoves.includes(x)).length === 2);

console.log(filteredCombinations);


1

既然我们需要在每个筛选后的数组中检查长度(匹配项),那么跳过对数组创建筛选,将其缩减为匹配元素的数量,直接检查该数量是否匹配即可,而不是使用length属性。

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(a=> a.reduce((r, v) => r + playerMoves.includes(v), 0)==2);

console.log('matching array: ', res)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接