This is an attempt in a tic tac toe game app. I have two arrays playerMoves
and winningCombinations
. Like this.
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]
];
I need to filter the winningCombination
array such that at-least and at-most two values of playerMoves
array matches with each array in winningCombination
.
findPossibleMove(playerMoves);
// should return [[0,1,2],[1,4,7], [0,4,8] ]
My attempt
function findPossibleMove(arr){
var found = 0;
return arr.forEach((item)=>{
winningCombinations.map((obj)=>{
if(obj.indexOf(item) !== -1) {
found++;
}
if(found===2){
return obj;
}
})
})
}
Three simple steps:
indexOf
function to check, if specified element from the subarray of winningCombinations
array is present in the playerMoves
array.Array#filter
function.2
, it means that two (no more, nor less) elements have appeared - it fulfills our condition - filter it once again with yet another 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));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加