Categories
JavaScript Answers

How to check if array contains all elements of another array with JavaScript?

Spread the love

Sometimes, we want to check if array contains all elements of another array with JavaScript.

In this article, we’ll look at how to check if array contains all elements of another array with JavaScript.

How to check if array contains all elements of another array with JavaScript?

To check if array contains all elements of another array with JavaScript, we call the every method.

For instance, we write

const array1 = [1, 2, 3];
const array2 = [1, 2, 3, 4];

const checker = (arr, target) => target.every((v) => arr.includes(v));
console.log(checker(array2, array1));

to call target.every`` with a callback that checks if every item vintargetis in thearrarray withincludes`.

Then we call checker with the 2 arrays to check.

Conclusion

To check if array contains all elements of another array with JavaScript, we call the every method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *