Ranjan Raj Shrestha
Ranjan Raj Shrestha

Reputation: 99

Checking the values of two Arrays using Includes

Is there any best way of find elements of two arrays?

In this code below I want to pass through this if the condition

I want the best way of solving this problem

const x =["a"]
const y =["a",3]
const z =["a",undefined,3]

for(let i=0;i<5;i++){
  x[1]=i
  console.log(x)
  if(x.includes(y)){
    console.log("i an in")
  }
  if(x.includes(z)){
    console.log("i am in")
  }
}

Upvotes: 0

Views: 107

Answers (1)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

If I'm not wrong, you want to check array x include the array y (or not) and vice versa.

Then you can use Array#every & Array#includes like below:

const x =["a"];
const y =["a", 3];
const z =["a", undefined, 3];

const checkInclude = (a, b) => b.every(v1 => a.includes(v1)); // The same as b.every(v1 => a.some(v2 => v1 === v2));

console.log("x include y: " + checkInclude(x, y));
console.log("y include x: " + checkInclude(y, x));
console.log("z include y: " + checkInclude(z, y));


The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Upvotes: 1

Related Questions