Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

How to check if an array is a subset of another array in JavaScript?

Let's say I have two arrays,

var PlayerOne = ['B', 'C', 'A', 'D'];
var PlayerTwo = ['D', 'C'];

What is the best way to check if arrayTwo is subset of arrayOne using javascript?

The reason: I was trying to sort out the basic logic for a game Tic tac toe, and got stuck in the middle. Here's my code anyway... Thanks heaps!

var TicTacToe = {


  PlayerOne: ['D','A', 'B', 'C'],
  PlayerTwo: [],

  WinOptions: {
      WinOne: ['A', 'B', 'C'],
      WinTwo: ['A', 'D', 'G'],
      WinThree: ['G', 'H', 'I'],
      WinFour: ['C', 'F', 'I'],
      WinFive: ['B', 'E', 'H'],
      WinSix: ['D', 'E', 'F'],
      WinSeven: ['A', 'E', 'I'],
      WinEight: ['C', 'E', 'G']
  },

  WinTicTacToe: function(){

    var WinOptions = this.WinOptions;
    var PlayerOne = this.PlayerOne;
    var PlayerTwo = this.PlayerTwo;
    var Win = [];

    for (var key in WinOptions) {
      var EachWinOptions = WinOptions[key];

        for (var i = 0; i < EachWinOptions.length; i++) {
          if (PlayerOne.includes(EachWinOptions[i])) {
            (got stuck here...)
          }

        }
        // if (PlayerOne.length < WinOptions[key]) {
        //   return false;
        // }
        // if (PlayerTwo.length < WinOptions[key]) {
        //   return false;
        // }
        // 
        // if (PlayerOne === WinOptions[key].sort().join()) {
        //   console.log("PlayerOne has Won!");
        // }
        // if (PlayerTwo === WinOptions[key].sort().join()) {
        //   console.log("PlayerTwo has Won!");
        // } (tried this method but it turned out to be the wrong logic.)
    }
  },


};
TicTacToe.WinTicTacToe();
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the solution:

Using ES7 (ECMAScript 2016):

const result = PlayerTwo.every(val => PlayerOne.includes(val));

Snippet:

const PlayerOne = ['B', 'C', 'A', 'D'];
const PlayerTwo = ['D', 'C'];

const result = PlayerTwo.every(val => PlayerOne.includes(val));

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...