'check if 2d array match or have the value of 1d array
let winningCombination = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7],
[1,5,9]]
let o = [5,8,6,7]
let x = [1,2,3,4,9];
var xMark = "X"
var oMark = "O"
function checkWinner(){
if(winningCombination.some(item => item.every((val,index) => val === o[index]))){
winner = oMark;
}else if (winningCombination.some(item => item.every((val,index) => val === x[index]))){
winner = xMark;
}
return winner;
}
how do I check if the 1d array matches the 2d array? when the x or o array gets larger the checkWinner method isn't working
Solution 1:[1]
Your code for checking if one team's marks is a winning combination is order dependent. It checks if the first move of the player is equal to the first move of the winning combination, even though order doesn't matter in rock paper scissors. It also won't check beyond the third move.
A fix would be to do something like:
winningCombination.some(item => item.every((val) => o.includes(val))
Or even shorter:
winningCombination.some(item => item.every(o.includes)
Or in English: For each winning combination, check every needed mark, and see if that mark is included ANYWHERE in the list of marks the player has set.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | codemaker 4 |
