Check if Array Includes All Values

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a JavaScript programming exercise that involves checking if all the elements in a given array are included in another array. Through this exercise, you will learn how to use Array.prototype.every() and Array.prototype.includes() to solve this problem efficiently. This lab will help you improve your understanding of JavaScript arrays and array methods.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28146{{"`Check if Array Includes All Values`"}} javascript/data_types -.-> lab-28146{{"`Check if Array Includes All Values`"}} javascript/arith_ops -.-> lab-28146{{"`Check if Array Includes All Values`"}} javascript/comp_ops -.-> lab-28146{{"`Check if Array Includes All Values`"}} end

Function to Check if an Array Includes All Values

If you want to check whether all the elements in an array values are included in another array arr, you can use the includesAll function in JavaScript.

To start using the function, open the Terminal/SSH and type node.

Here's how the includesAll function works:

  • It uses Array.prototype.every() and Array.prototype.includes() methods to check if all elements in values are included in arr.
  • If all elements in values are included in arr, the function will return true. Otherwise, it will return false.
const includesAll = (arr, values) => values.every((v) => arr.includes(v));

Here's an example of how to use the includesAll function:

includesAll([1, 2, 3, 4], [1, 4]); // true
includesAll([1, 2, 3, 4], [1, 5]); // false

Summary

Congratulations! You have completed the Check if Array Includes All Values lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like