简体   繁体   中英

Find if few array items exists in any one of many arrays?

Have these 2 Javascript arrays

// The player which has a "winning" combination (1, 5, 9)
player1Cells = [ 5, 9, 1, 6] 
// Player which doesnt have a "winning" combination
player2Cells = [ 2, 1, 4, 8]

A player has a "winning" combination if 3 of their numbers match one of the arrays in this array:

winningCombinations = [
    [1, 2, 3], [4, 5, 6], [7, 8, 9],
    [1, 4, 7], [2, 5, 8], [3, 6, 9],
    [1, 5, 9], [3, 5, 7]
];

In the example, player1Cells has a winning combination - 1, 5, 9. The other player doesn't

I figured there is a way to loop through the winningCombinations in some way, and compare it against the player compare but I don't know best approach to comparing these in an efficient way.

You can use some method on the winning array and then filter method to check if player has more than 3 matches as current array in some loop.

 const w = [[1, 2, 3], [4, 5, 6], [7, 8, 9],[1, 4, 7], [2, 5, 8], [3, 6, 9],[1, 5, 9], [3, 5, 7]]; const player1Cells = [ 5, 9, 1, 6]; const player2Cells = [ 2, 1, 4, 8]; function check(arr, p) { return arr.some(a => { const match = p.filter(e => a.includes(e)); return match.length >= 3; }) } console.log(check(w, player1Cells)); console.log(check(w, player2Cells));

You may use:

Working Example:

 let player1Cells = [5, 9, 1, 6]; let player2Cells = [2, 1, 4, 8]; let winningCombinations = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ]; let checker = function(w, p) { return w.some(a => a.every(v => p.includes(v))); } console.log(checker(winningCombinations, player1Cells)); console.log(checker(winningCombinations, player2Cells));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM