How to check if an array is a subset of another array in 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);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)