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

user3157674
  • 65
  • 1
  • 8

1 Answers1

2

Iterate over a with some. If the length of the inner array doesn't match the length of b immediately return false, otherwise 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
  • 61,948
  • 13
  • 68
  • 95