繁体   English   中英

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

[英]How to compare an array to an array of arrays?

这是一个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]
      ];

我需要过滤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函数过滤掉它。
  • 如果返回的,已过滤的子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)); 

您可以使用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); 

因为我们必须检查每个过滤数组中的长度(匹配项),如何跳过针对数组创建过滤后的数组并将其reducing为多个匹配元素并直接检查它而不是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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM