Athreya Daniel
Athreya Daniel

Reputation: 17

Check if array contains another array JS

If I have 2 arrays like so:

arr1 = [[1,2]]
arr2 = [1,2]

How do I check if arr2 is in arr1? I have tried the following:

arr1.includes(arr2)

But this returns false. Is there an easy way to do this in JS?

EDIT: I would also like to get the true index of arr2 in arr1. For example:

arr1.indexOf(arr2) => 0

Because arr2 is the first index of arr1.

Upvotes: 0

Views: 75

Answers (3)

Majed Badawi
Majed Badawi

Reputation: 28434

You can write a simple function that searches the list of arrays for arr2, keeping in mind that you need to sort before comparison. Here are some examples to get the index of arr2 if it was found as well:

let arr1 = [[1,2]];
let arr2 = [1,2];
console.log(arrayInList(arr1,arr2));
arr2 = [1,3]
console.log(arrayInList(arr1,arr2));
function arrayInList(arr1, arr2){
     if(!arr1 || arr1.length==0 || !arr2 || arr2.length==0)
          return false;
     arr2 = arr2.sort();
     let foundIndex = -1;
     for(let i = 0; i < arr1.length; i++){
          let current = arr1[i].sort();
          if(current.length != arr2.length)
               continue;
          let areEqual = true;
          for(let j = 0; j < arr2.length; j++){
               if(arr2[j] != current[j]){
                    areEqual = false;
                    break;
               }
          }
          if(!areEqual){
               continue;
          }else{
               foundIndex = i;
               break;
          }
     }
     return foundIndex;
}

A faster solution would be storing them in an object as follows:

let arr1 = [[1,2]];
let arr2 = [1,2];
console.log(arrayInList(arr1,arr2));
arr2 = [1,3]
console.log(arrayInList(arr1,arr2));
function arrayInList(arr1, arr2){
     if(!arr1 || arr1.length==0 || !arr2 || arr2.length==0)
          return false;
     arr2 = arr2.sort();
     let set = {};
     for(let i = 0; i < arr1.length; i++)
          set[arr1[i].sort()] = i;
     return (set[arr2]!=undefined)?set[arr2]:-1;
}

Upvotes: 1

Waffles
Waffles

Reputation: 407

Why not just use the Array.isArray?

   let arr1 = [[1,2]];
   let arr2 = [1,2];
   for (let i = 0; arr1.length; i++) {
       if (Array.isArray(arr1[i])) {
         console.log("Found array!")
       }
   }

Upvotes: 1

roygbiv
roygbiv

Reputation: 369

You can do something like this:

arr1 = [[1,2]]
arr2 = [1,2]
a = JSON.stringify(arr1);
b = JSON.stringify(arr2);

And check the value of the index, it will return -1 if arr2 is not inside arr1

a.indexOf(b);

Upvotes: 0

Related Questions