How to find elements of JavaScript array by multiple values?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to find elements of JavaScript array by multiple values −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Find elements of JavaScript array by multiple values</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to see if arr contains all elements of arr1 or not</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let arr = [11, 44, 22, 16, 25, 91, 58];
   let arr1 = [22, 91, 11];
   let contain = arr1.every((item) => arr.includes(item));
   BtnEle.addEventListener("click", () => {
      if (contain) resEle.innerHTML = "The arr contains all elements of arr1";
      else resEle.innerHTML = "The arr doesn't contain all elements of arr1";
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 18-Jul-2020 08:54:45
Advertisements