How to check if an array is a subset of another array in JavaScript?
JavascriptArraysJavascript Problem Overview
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();
Javascript Solutions
Solution 1 - Javascript
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);
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);
Solution 2 - Javascript
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 });
Solution 3 - Javascript
You can use this simple piece of code.
PlayerOne.every(function(val) { return PlayerTwo.indexOf(val) >= 0; })
Solution 4 - Javascript
function isSubsetOf(set, subset) {
return Array.from(new Set([...set, ...subset])).length === set.length;
}
Solution 5 - Javascript
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
Solution 6 - Javascript
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
Solution 7 - Javascript
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
Solution 8 - Javascript
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.