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

2

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.