如何检查一个数组是否是 JavaScript 中另一个数组的子集?

假设我有两个数组,

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

使用 javascript 检查 arrayTwo 是否是 arrayOne 的子集的最佳方法是什么?

原因是: 我正在尝试整理一个游戏井字游戏的基本逻辑,结果卡在了中间。不管怎样,这是我的代码... 非常感谢!

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();
70923 次浏览

If you are using ES6:

!PlayerTwo.some(val => PlayerOne.indexOf(val) === -1);

If you have to use ES5, use a polyfill for the some function the Mozilla documentation, then use regular function syntax:

!PlayerTwo.some(function(val) { return PlayerOne.indexOf(val) === -1 });

You can use this simple piece of code.

PlayerOne.every(function(val) { return PlayerTwo.indexOf(val) >= 0; })

If PlayerTwo is subset of PlayerOne, then length of set(PlayerOne + PlayerTwo) must be equal to length of set(PlayerOne).

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


// Length of set(PlayerOne + PlayerTwo) == Length of set(PlayerTwo)


Array.from(new Set(PlayerOne) ).length == Array.from(new Set(PlayerOne.concat(PlayerTwo)) ).length

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

Using ES5 (ECMAScript 2009):

var result = PlayerTwo.every(function(val) {


return PlayerOne.indexOf(val) >= 0;


});

Snippet:

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


var result = PlayerTwo.every(function(val) {


return PlayerOne.indexOf(val) >= 0;


});


console.log(result);


Here is answer the question at the comment below:

How do we handle duplicates?

Solution: It is enough to add to the above solution, the accurate condition for checking the number of adequate elements in arrays:

const result = PlayerTwo.every(val => PlayerOne.includes(val)
&& PlayerTwo.filter(el => el === val).length
<=
PlayerOne.filter(el => el === val).length
);

Snippet for first case:

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


const result = PlayerTwo.every(val => PlayerOne.includes(val)
&& PlayerTwo.filter(el => el === val).length
<=
PlayerOne.filter(el => el === val).length
);


console.log(result);

第二个案例的代码段:

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


const result = PlayerTwo.every(val => PlayerOne.includes(val)
&& PlayerTwo.filter(el => el === val).length
<=
PlayerOne.filter(el => el === val).length
);


console.log(result);

This seems most clear to me:

function isSubsetOf(set, subset) {
for (let i = 0; i < set.length; i++) {
if (subset.indexOf(set[i]) == -1) {
return false;
}
}
return true;
}

It also has the advantage of breaking out as soon as a non-member is found.

Here is a solution that exploits the set data type and its has function.

let PlayerOne = ['B', 'C', 'A', 'D', ],
PlayerTwo = ['D', 'C', ],
[one, two] = [PlayerOne, PlayerTwo, ]
.map( e => new Set(e) ),
matches = Array.from(two)
.filter( e => one.has(e) ),
isOrisNot = matches.length ? '' : ' not',
message = `${PlayerTwo} is${isOrisNot} a subset of ${PlayerOne}`;
console.log(message)


Out: D,C is a subset of B,C,A,D
function isSubsetOf(set, subset) {
return Array.from(new Set([...set, ...subset])).length === set.length;
}

If you want to compare two arrays and take also order under consideration here is a solution:

  let arr1 = [ 'A', 'B', 'C', 'D' ];
let arr2 = [ 'B', 'C' ];
arr1.join().includes(arr2.join()); //true


arr2 = [ 'C', 'B' ];
arr1.join().includes(arr2.join()); //false