簡體   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