繁体   English   中英

Javascript:在数组数组中搜索数组

[英]Javascript: Search for an array in an array of arrays

我正在寻找在数组数组中搜索包含给定数组元素的数组实例的最佳方法。

现在,我知道那是一条令人困惑的路线。 因此,这里有一个示例来说明这种情况。

我有一个搜索集,它是一个包含9个项目的数组,代表9个单元的游戏板。 的值可以是10null

var board = [1, 0, 1, 1, 0, 1, 0, 0, null];

我还有一个结果集,它是一个数组数组:

var winningCombos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

winningCombo每个数组代表board数组中的索引 ,即获胜组合。

有8种获胜组合。

每个获胜组合都是一个由3个指数组成的组,如果它们的值均为1,则将获胜。

即要赢,董事会可能是:

board = [1,1,1,0,0,0,null,null,0]; // Index 0,1, and 2 are 1, matching winningCombos[0]

要么

board = [null,null,1,0,1,0,1,null,0]; // Index 2,4, and 6 are 1, matching winningCombos[7]

我的问题是:

用Javascript执行此操作的方式是什么(也许使用ES6)?

到目前为止,我想出的是:

 const win = [[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 board = [null,null,1,0,1,0,1,null,0]; let score = []; board.forEach(function(cell, index) { if(cell === 1) score.push(index); }); console.log(score); console.log(win.indexOf(score) > -1) 

但我有一个艰难的时间找到数组的数组数组 尽管score[2,4,6]且此精确数组存在于win ,但由于我认为Java中对象平等的工作方式,因此它不会出现在结果中。

简而言之,我想看看win是否存在score

我找到了这个解决方案,但似乎很hacky。 有没有更好的方法来解决这个问题?

您可以使用Array.prototype.some()Array.prototype.every()检查win每个元素, score

 const win = [ [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 board = [null, null, 1, 0, 1, 0, 1, null, 0]; let score = []; board.forEach(function(cell, index) { if (cell === 1) score.push(index); }); console.log(score); let bool = win.some(function(arr) { return arr.every(function(prop, index) { return score[index] === prop }) }); console.log(bool); 

使用ES6,您可以将win数组映射到这些位置中每个位置的实际值:

const win = [[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 board = [null,null,1,0,1,0,1,null,0];
let winning_spots = win.map((spots) => spots.map((i) => board[i]));
>>> winning_spots
[[null, null, 1], [0, 1, 0], [1, null, 0], [null, 0, 1], [null, 1, null], [1, 0, 0], [null, 1, 0], [1, 1, 1]]

然后,我们可以过滤具有1或0的所有值:

let one_winners = winning_spots.filter((spots) => spots.every((e) => e == 1));
let zero_winners = winning_spots.filter((spots) => spots.every((e) => e == 0));
>>> one_winners
[[1, 1, 1]]
>>> zero_winners
[]

最后,如果我们想确定是否有赢家,只需检查长度即可:

let is_winner = (one_winners.length + zero_winners.length) > 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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