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 中,但它没有出现在结果中,因为对象相等在 Javascript 中的工作方式我假设.

简而言之,我试图查看 score 是否存在于 win

我找到了 this 解决方案,但它似乎很老套。有没有更好的方法来处理这个问题?

使用 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

您可以使用Array.prototype.some()Array.prototype.every()来检查winscore

的每个元素

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);