Reputation: 843
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();
Upvotes: 82
Views: 91759
Reputation: 47
Here's a better example, that covers cases with duplicates in the subset array:
function isArraySubset(source, subset) {
if (subset.length > source.length) return false;
const src = [...source]; // copy to omit changing an input source
for (let i = 0; i < subset.length; i++) {
const index = src.indexOf(subset[i]);
if (index !== -1) {
src.splice(index, 1);
} else {
return false;
}
}
return true;
}
console.log(isArraySubset(['b', 'c', 'a', 'd'], ['d', 'c'])); // true
console.log(isArraySubset(['b', 'c', 'a', 'd'], ['d', 'c', 'c'])); // false
Upvotes: 0
Reputation: 129
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
Upvotes: 2
Reputation: 34593
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);
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);
Snippet for second case:
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);
Upvotes: 157
Reputation: 1123
function isSubsetOf(set, subset) {
return Array.from(new Set([...set, ...subset])).length === set.length;
}
Upvotes: 11
Reputation: 27476
You can use this simple piece of code.
PlayerOne.every(function(val) { return PlayerTwo.indexOf(val) >= 0; })
Upvotes: 11
Reputation: 2836
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
Upvotes: 0
Reputation: 289
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.
Upvotes: -1
Reputation: 27476
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
Upvotes: 8
Reputation: 6299
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 });
Upvotes: 21