0

I have an array

a = [ [1,2],[3,4] ]

b = [1,2]

I want to find if b is in a, how would i do that?

I tried using

a.includes(b) 

or

a.find(e => e == b)

but both don't work

1 Answers1

0

Iterate over a with some. If the length of the inner array doesn't match the length of b immediately return false, other use every to check that the inner array includes all of the elements of b. This will also check when elements are out of order like [2, 1] should you need to do so.

const a = [ [ 1, 2 ], [ 3, 4 ] ];
const b = [ 1, 2 ];
const c = [ 1, 2, 3 ];
const d = [ 3 ];
const e = [ 3, 4 ];
const f = [ 2, 1 ];

function check(a, b) {
  return a.some(arr => {
    if (arr.length !== b.length) return false;
    return b.every(el => arr.includes(el));
  });
}

console.log(check(a, b));
console.log(check(a, c));
console.log(check(a, d));
console.log(check(a, e));
console.log(check(a, f));
Andy
  • 53,323
  • 11
  • 64
  • 89