How to test if one array is a subset of another with JavaScript?

Sometimes, we want to test if one array is a subset of another with JavaScript.

In this article, we’ll look at how to test if one array is a subset of another with JavaScript.

How to test if one array is a subset of another with JavaScript?

To test if one array is a subset of another with JavaScript, we can use the JavaScript array’s includes and every methods.

For instance, we write:

const a1 = [1, 2, 3]
const a2 = [1, 2, 3, 4, 5, 6]
const isSubset = a1.every(a => {
  return a2.includes(a)
})
console.log(isSubset)

We define 2 arrays a1 and a2.

And we call every on a1 with a callback that checks if each element in a1 is included in a2 with the includes method.

Therefore, the console log should log true since every element in a1 is in a2.

Conclusion

To test if one array is a subset of another with JavaScript, we can use the JavaScript array’s includes and every methods.