2017-07-17 175 views
13

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

回答

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

2

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

0

,因为我们要检查,长度(匹配项)在每个过滤的数组中,如何跳过对阵列的过滤数组创建和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)

相关问题