[英]How to compare an array to an array of arrays?
這是一個tic tac toe游戲應用程序的嘗試。 我有兩個數組playerMoves
和winningCombinations
。 像這樣。
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));
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.