How to check whether multiple values exist within a JavaScript array


We are required to write a JavaScript function that takes in two arrays of Numbers and checks whether all the elements of the first array exist in the second or not.

Following are our arrays −

const arr1 = [34, 78, 89];
const arr2 = [78, 67, 34, 99, 56, 89];

Let's write the code and check for multiple values −

Example

const arr1 = [34, 78, 89];
const arr2 = [78, 67, 34, 99, 56, 89];
const contains = (first, second) => {
   const indexArray = first.map(el => {
      return second.indexOf(el);
   });
   return indexArray.indexOf(-1) === -1;
}
console.log(contains(arr1, arr2));

Output

The output in the console will be −

true

Updated on: 31-Aug-2020

842 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements