Javascript:在数组数组中搜索数组 [英] Javascript: Search for an array in an array of arrays

查看:52
本文介绍了Javascript:在数组数组中搜索数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking at the best way to search for an instance of an array containing the elements of a given array, in an array of arrays.

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

Now, I understand that that's a confusing line. So here's an example to illustrate the scenario.

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

I have a search set which is an array with 9 items, representing a game board of 9 cells. The values can be 1, 0 or null:

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

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

I also have a result set, which is an array of arrays:

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 数组中的指数,是获胜组合.

Each array in winningCombo represents indices in the board array, that are winning combinations.

有8种获胜组合.

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

Each winning combination is a group of 3 indices, that would win, if their values are all 1.

即为了赢得胜利,董事会可能是:

i.e. to win, the board could be:

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]

我的问题是:

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

What I have come up with so far is this:

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)

但是我很难在数组中找到 array .尽管 score [2,4,6] ,并且此确切的数组存在于 win 中,但不会显示在结果中,因为我假设对象相等性在Javascript中的工作方式.

But I'm having a tough time finding the array in the array of arrays. Although the score is [2,4,6] and this exact array exists in win, it doesn't show up in the result, because of the way object equality works in Javascript I assume.

我找到了解决方案,但它似乎很不可靠.有更好的方法来解决这个问题吗?

I found this solution, but it seems quite hacky. Is there a better way to handle this?

推荐答案

您可以使用 Array.prototype.some() Array.prototype.every()检查 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 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);

这篇关于Javascript:在数组数组中搜索数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆