[英]How to compare an array to an array of arrays?
This is an attempt in a tic tac toe game app. 这是一个tic tac toe游戏应用程序的尝试。 I have two arrays
playerMoves
and winningCombinations
. 我有两个数组
playerMoves
和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
. 我需要过滤
winningCombination
阵列,使得在-至少和在最的两个值playerMoves
阵列,以在每个阵列匹配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. indexOf
函数检查,如果指定的元素来自winningCombinations
数组的子数组,则存在于playerMoves
数组中。 Array#filter
function. Array#filter
函数过滤掉它。 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
. 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));
You can use filter
and includes
to achieve that: 您可以使用
filter
和includes
来实现:
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);
since we have to check with the length (matched item) in each filtered array, how about skipping creation of filtered array against array and reducing
it to a number of matched element and check directly with that instead of the length
? 因为我们必须检查每个过滤数组中的长度(匹配项),如何跳过针对数组创建过滤后的数组并将其
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.