Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array contains/includes sub array

I need to check if an array contains another array. The order of the subarray is important but the actual offset it not important. It looks something like this:

var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3]; 

var sub = [777, 22, 22]; 

So I want to know if master contains sub something like:

if(master.arrayContains(sub) > -1){
    //Do awesome stuff
}

So how can this be done in an elegant/efficient way?

like image 494
Victor Axelsson Avatar asked Dec 08 '15 09:12

Victor Axelsson


People also ask

How to check if a JavaScript array contains a certain value?

To check if a JavaScript array contains a certain value or element, you can use the includes () method of the Array object. The includes () method returns the Boolean true if your array contains the value you specified as its argument. Otherwise, the method returns false.

What is array includes() method in JavaScript?

The array includes () is a built-in JavaScript method that defines whether the array contains the specified element or not. The includes () function accepts element and start parameters and returns true or false as output depending on the result. The includes () method is case sensitive.

How to use the includes() array method to search for a value?

Learn how to use the includes () Array method to search for a certain value in JavaScript To check if a JavaScript array contains a certain value or element, you can use the includes () method of the Array object. The includes () method returns the Boolean true if your array contains the value you specified as its argument.

What is the syntax of array contain in JavaScript?

Syntax of JavaScript Array Contain are given below: The above syntax of includes () method is explained in detail below: sampleArray: It can be an array variable containing any number of elements in which you want to determine whether it contains the particular value or not.


1 Answers

var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3]; 

var sub = [777, 22, 22]; 

console.log(master.join(',').includes(sub.join(',')))

//true

You can do this by simple console.log(master.join(',').includes(sub.join(','))) this line of code using include method

like image 157
Mohmadhaidar devjiyani Avatar answered Sep 21 '22 03:09

Mohmadhaidar devjiyani