Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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

Solution 2:

Using ES6 you can map the win array to the actual values at each one of those locations:

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

Then we can filter by which ones have all of either 1's or 0's:

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

Finally, if we want to find whether there is a winner, just check the lengths:

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

Post a Comment for "Javascript: Search For An Array In An Array Of Arrays"