nikjohn nikjohn - 22 days ago 7
Javascript Question

Javascript: Search for an array in an array of arrays

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.

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]]


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

There are 8 winning combinations.

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]


or

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


My question is:

What is the way in Javascript to perform this operation (maybe with ES6)?



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)





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.

In a nutshell, I'm trying to see if
score
exists in
win



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

Answer

You can use Array.prototype.some(), Array.prototype.every() to check each element of 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);

Comments