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

ano*_*ran 14 javascript arrays underscore.js lodash

这是一个tic tac toe游戏应用程序的尝试.我有两个数组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]
      ];
Run Code Online (Sandbox Code Playgroud)

我需要过滤winningCombination数组,使得至少和最多两个playerMoves数组的值与每个数组匹配winningCombination.

findPossibleMove(playerMoves);
// should return [[0,1,2],[1,4,7], [0,4,8] ]
Run Code Online (Sandbox Code Playgroud)

我的尝试

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

kin*_*ser 9

三个简单的步骤:

  • 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));
Run Code Online (Sandbox Code Playgroud)