Check if Array Includes Any Values

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring a JavaScript function that checks if an array includes any values from another array. We will be using the Array.prototype.some() and Array.prototype.includes() methods to implement the includesAny() function. By the end of this lab, you will have a better understanding of how to efficiently check for the presence of values in arrays using JavaScript.


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-28147{{"`Check if Array Includes Any Values`"}} javascript/data_types -.-> lab-28147{{"`Check if Array Includes Any Values`"}} javascript/arith_ops -.-> lab-28147{{"`Check if Array Includes Any Values`"}} javascript/comp_ops -.-> lab-28147{{"`Check if Array Includes Any Values`"}} end

Checking if an Array Includes Any Values

To start practicing coding, open the Terminal/SSH and type node.

To check if an array includes at least one element from another array, use Array.prototype.some() and Array.prototype.includes(). Here is an example function:

const includesAny = (arr, values) => values.some((v) => arr.includes(v));

You can call this function and pass in the two arrays you want to compare as arguments. The function will return a boolean value indicating whether at least one element of values is included in arr. Here are some examples:

includesAny([1, 2, 3, 4], [2, 9]); // true
includesAny([1, 2, 3, 4], [8, 9]); // false

Summary

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

Other JavaScript Tutorials you may like