Finding the index position of an array inside an array JavaScript


Suppose, we have an array of arrays like this −

const arr = [
   [1,0],
   [0,1],
   [0,0]
];

We are required to write a JavaScript function that takes in one such array as the first argument and an array of exactly two Numbers as the second argument.

Our function should check whether or not the array given by second input exists in the original array of arrays or not.

Example

const arr = [ [1,0], [0,1], [0,0] ];
 const sub = [0, 0];
const matchEvery = (arr, ind, sub) => arr[ind].every((el, i) => el == sub[i]);
const searchForArray = (arr = [], sub = []) => {
   let ind = -1;
   let {
      length: len } = arr;
      while (len--) {
         if (arr[len].length === sub.length && matchEvery(arr, len, sub)){
            ind = len;
            break;
      };
   };
   return ind;
};
console.log(searchForArray(arr, sub));

Output

And the output in the console will be −

2

Updated on: 23-Nov-2020

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements